Reputation: 65
Hey i am dealing with file handling in c++... I am new to file handling .... I want to append the content in front of file everytime i write into the file........
i have opened a file using..... fstream fi("user.txt",ios::app);
but this always append the content at end of file .....
I have written a c++ code using .....
Fstream fi("user.txt",ios::app); fi<<"john is a great boy"<
Fstream fi("user.txt",ios::app);
fi<<"john is a great boy"<<endl;
actual result: It is always appending my content at end of file...
Expected: It should always append content in front of file....
Upvotes: 1
Views: 588
Reputation: 25536
First question would be: Why do you want to do so at all?
Then with file processing, this is going to get tricky, because this is not how files work on OS level – while appending usually is supported natively, this is not the case for prepending (and thus there's no support for in C++ STL either). So you would need to write out the new lines to some temporary file and then append the previous contents afterwards all the time. No way around on Windows, Linux, BSD and derivates.
If you really insist on, you might write your own stream class based on standard file streams hiding all this work away. An alternative variant might read the output file only once, keep all the lines in memory, handle the new lines appropriately and print the lines back to file only once on closing the stream object. Drawback: if the application crashes, quite a number of lines might get lost. You could either use a std::deque
and prepend the new lines or read the lines in reverse order into a std::vector
, append the new lines and then print to file using reverse iterators.
Likely, though, you are better off just appending to the files. You might then write a separate application inverting the line order – advantage of: You'd be doing the inversion work only once, reading from the back can be done rather efficiently and on writing the new output file, you'd only append again. Alternatively, you might write your own file viewer application presenting the lines in inverted order (again reading from back, if size is too large, or just keeping all the lines in memory at once).
Upvotes: 2
Reputation: 19
If your file is not very large, you may consider by dumping file content to stringstream ss
first, add your newer content in front of ss
, and write it back to file.
Upvotes: 0
Reputation: 1290
I think the only way you can do that is by writing your content into another file then append the old lines to it.
Upvotes: 0