File is not being created (very simple code)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream tableFile;
    tableFile.open("table_file.txt");

    if (!tableFile)
    {
        cout << "\nSorry. There was an error writing the student data to a file.\n\n";
    }

return 0;
}
Try ofstream or ifstream. Or read this -> http://www.cplusplus.com/reference/fstream/basic_fstream/open/
Last edited on
strangely, ofstream is the only one that works. I'd really prefer to use fstream in my program though...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
    fstream fs;
    fs.open ("test.txt", fstream::out);

    if (!fs)
        cout<<"ERROR";
    else
    {
        cout<<"Writing to file...";
        fs << "Testing 1...2...3...";
        fs.close();
    }
    return 0;
}

Works for me. It could be that you failed to specify the mode you were opening the file in. If you check the directory where your project is, you should have a test.txt with the correct content after you run this.

Changing line 10 to fs.open ("test.txt", fstream::out | fstream::app); would make you add to the end of the file if it already exists, and create it if it doesn't.
Last edited on
Also of interest, you can use fstream the other way afterwards to read in information from the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
    string fin;
    fstream fs;
    fs.open ("test.txt", fstream::in);

    if (!fs)
        cout<<"ERROR";
    else
    {
        cout<<"Reading from file...\n";
        getline(fs, fin);
        cout<<"\nThe file contents are: \n"<<fin;
        fs.close();
    }
    cout<<endl;
    return 0;
}

Reading from file...

The file contents are:
Testing 1...2...3...

Last edited on
Topic archived. No new replies allowed.