I am trying to add elements into a .json
file between []
as last.
How can I move the cursor to add elements between [...]
with efficiently with std::ofstream
?
I have tried several open modes but there are strange things. First I created this question about not able to use the file streaming for read and write because of the overwrite issue.
#include <iostream>
#include <fstream>
int main ()
{
char errmsg[2048];
std::ofstream ostream;
ostream.exceptions(std::ios_base::badbit);
try
{
ostream.open("LS22731.json", std::fstream::ate | std::fstream::in);
strerror_s(errmsg, 2048, errno);
std::cout << "Error (" << errno << "): " << errmsg << std::endl;
if (ostream && ostream.is_open())
{
auto ppos = ostream.tellp();
std::streampos sub = 1; //
std::cout << "Tellp: " << ppos << std::endl; // Always show zero but file has large data
if (ppos > 1)
ostream.seekp(ppos - sub) << "aa";
ppos = ostream.teelp();
std::cout << "New tellp: " << ppos << std::endl;
ostream.close();
}
}
catch (std::ios_base::failure& fb)
{
std::cout << "Failure: " << fb.what() << std::endl;
char errmsg[2048];
strerror_s(errmsg, 2048, errno);
std::cout << "Error (" << errno << "): " << errno << std::endl;
}
}
I searched about open modes then I found this but is it good to open file with both mode std::fstream::ate | std::fstream::in
together for std::ofstream
? And when I open the file with std::fstream::out
mode it is rewriting so deleting whole document,
std::fstream::out
: Delete all contents of the file (overwrite)std::fstream::app
: Cannot move the cursor with seekpstd::fstream::ate
: Delete all contents of the file (overwrite)std::fstream::binary
: Delete all contents of the file (overwrite)std::fstream::ate | std::fstream::app
: Cannot move the cursor with seekpstd::fstream::ate | std::fstream::out
: Delete all contents of the file (overwrite)std::fstream::ate | std::fstream::in
: Can move the cursor but not insert delete all after.
I don't want to use c FILE
.