I'm having some difficulty getting my program to write into a file using ofstream.
I checked my code but I can't find the error. Everything runs to completion but it doesn't write into the file.
#include <iostream>
usingnamespace std;
int main() {
FILE *readtest = fopen ("readthis.txt", "w+"); //create text file for read/write.
if ( readtest != NULL ) {
fprintf ( readtest, "Hi" );
}
return 0;
}
EDIT
the w+ in this code creates the file and if such file is already created the w+ will delete and replace the old file with new one created. To only open a file and write to it use r+
Rather than just trying variations of the same code. you should check the status of the file and display a suitable message if a problem is found.
For example you can test if (!file.open()) before output, and if (!file.good()) afterwards.
But I suspect iHutch105 has hit the nail on the head, you may be looking in the wrong location (directory or subdirectory) for the file.
It turns out that the issue was because I am on a Mac. Basically, I needed an absolute path, unlike windows where the file would be created where the .exe file is.