I am writing a program that needs to read from one file and write to another. Using fstream
, I implemented the reading part, but the writing part didn't work no matter what I tried.
I tried the 'example programs' from all sorts of websites, but none of them worked. I tried changing things like file.isOpen() == false
to !file
and all that, but still nothing.
It doesn't matter if file exists or not, ofstream
functions just don't seem to work.
From what I read, it seems to be a permissions issue? Besides that, I have no other clue. There are no errors or abnormal statuses reported. Everything before and after works fine while ofstream
functions are just ignored.
I am using Visual Studio Code, windows 10. Snippet from w3schools I tried.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
CodePudding user response:
@timebender
I tried following code using g .exe(cygwin windows)
#include <string.h>
#include <sys/errno.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Create and open a text file
ofstream MyFile("filename.txt", ios::app|ios::out);
if ( MyFile.is_open() )
{
cout << "is_open pass\n";
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!\n";
// Close the file
MyFile.close();
cout << "closed file\n";
}
else
{
cout << "ofstream filename.txt failed\n";
cout << strerror(errno) << "\n";
}
return 0;
}
$ g 73174678.cpp -o ./a.out;a.out
$ ./a.out
is_open pass
closed file
$ cat "filename.txt"
Files can be tricky, but it is fun enough!
$ g .exe 73174678.cpp -o ./a.exe;./a.exe
$ ./a.exe
is_open pass
closed file
CodePudding user response:
Could be writing the file somewhere you don't expect?
See: https://en.cppreference.com/w/cpp/filesystem/current_path