I am trying to write to a file, read from the file and then print to console:
#include
#include
#include
int main() {
//open/create a text file
std::fstream myFile("messagelogs.txt", std::ios::out | std::ios::in | std::ios::app);
//write to file
myFile << "Hello World\nBye World\n" << std::endl;
//read from file
std::string readFile;
std::getline(myFile, readFile);
while (myFile) {
std::cout << readFile << '\n';
std::getline(myFile, readFile);
}
//close file
myFile.close();
return 0;
}
The problem is that when I run the code, nothing is printing on the console, although it successfully writes to the file.
When I was debugging, I found that nothing is written to the file until myFile.close(); , so readFile is null and nothing prints on the console.
I was wondering why the text isn't being written to the file after myFile << "Hello World\nBye World\n" << std::endl; rather than when the file is closed?
I was also wondering how I can fix this problem - should I close the file after writing and then reopen the file to read again?