Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ ofstream doesn't modify files. Even the tutorial examples

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}

>Solution :

@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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading