Question

I am trying to pass document name to open in fstream, it works with ofstream but not with fstream.

Example, this works fine...

void TestFunction (ofstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName);
    test << "test test test" << endl;
    test.close();
}

int main ()
{
    ofstream database;
    char FileName[100]="database.txt";

    TestFunction(database, FileName);
    getchar();
    return 0;
}

Example 2, this doesn't create file...

void TestFunction (fstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName);
    test << "test test test" << endl;
    test.close();
}

int main ()
{
    fstream database;
    char FileName[100]="database.txt";

    TestFunction(database, FileName);
    getchar();
    return 0;
}

Anyone have any suggestions what am I doing wrong?

EDIT After some more Googling I found answer to my question, should I delete my question now or? c++: ifstream open problem with passing a string for text file name

Was it helpful?

Solution

To make your second verson work, you could add the flag ios_base::out:

void TestFunction (fstream &test,char FileName []){
    cout << "test !!!" << endl;
    test.open(FileName, std::ios::out);
    //                  ^^^^^^^^^^^^
    test << "test test test" << endl;
    test.close();
}

If you just want to write content to a file, you could choose more specific version which is std::ofstream.

Because basic_ofstream constructor is designed to take const char* as input parameter, so it doesn't acceptstd::string`, however, this is changed in C++11.

explicit basic_ofstream( const char* filename,
                ios_base::openmode mode = ios_base::out );  // before C++11

explicit basic_ofstream( const string& filename,                                  
                ios_base::openmode mode = ios_base::out );  //  (since C++11)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top