Reputation: 588
I would like to write a new line with a string on a file when the writeToFile function is called. Is that possible without clearing the previous line or the whole txt?
void writeToFile(string str) {
ofstream fileToWrite;
fileToWrite.open("C:/Users/Lucas/Documents/apps/resultado.txt");
if(fileToWrite.good()) {
//write the new line without clearing the txt
//fileToWrite << str won't work for this reason
}
fileToWrite.close();
}
Upvotes: 0
Views: 128
Reputation: 490788
Yes. Look up std::ios_base::ate
and std::ios_base::app
.
void write_to_file(std::string const &str) {
std::ofstream fileToWrite("C:/Users/Lucas/Documents/apps/resultado.txt",
std::ios_base::app);
fileToWrite << str << "\n";
}
In this case, the difference between the two is irrelevant, but ios_base::ate
means when you open the file, it's positioned at the end, so what you write is added to the end -- but if you want, you can seek to earlier parts of the file and overwrite what's there. With ios_base::app
, before you do any write, it'll automatically seek to the end, so any writing you do gets appended to the end, rather than overwriting any existing data.
Upvotes: 2