I have a problem with appending a text to a file. I open an ofstream
in append mode, still instead of three lines it contains only the last:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream file("sample.txt");
file << "Hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "Again hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "And once again - hello, world!" << endl;
file.close();
string str;
ifstream ifile("sample.txt");
while (getline(ifile, str))
cout << str;
}
// output: And once again - hello, world!
So what's the correct ofstream
constructor for appending to a file?
In order for us to append to a file, we must put the ofstream() function in append mode, which we explain in the next paragraph. With the full line, ofstream writer("file1. txt", ios::app);, we now create a connection to open up the file1. txt file in order to append contents to the file.
Begin Open that file a1. txt as output file stream class object to perform output operation in append mode using fout file reference. If the file exists then Appending text to that file. Close fout.
It truncates by default.
basic_ios::rdbufManages the associated stream buffer. 1) Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer.
I use a very handy function (similar to PHP file_put_contents)
// Usage example: filePutContents("./yourfile.txt", "content", true);
void filePutContents(const std::string& name, const std::string& content, bool append = false) {
std::ofstream outfile;
if (append)
outfile.open(name, std::ios_base::app);
else
outfile.open(name);
outfile << content;
}
When you need to append something just do:
filePutContents("./yourfile.txt","content",true);
Using this function you don't need to take care of opening/closing. Altho it should not be used in big loops
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With