0

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

Community
  • 1
  • 1
Cokaric
  • 51
  • 1
  • 8

1 Answers1

2

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)
billz
  • 44,644
  • 9
  • 83
  • 100
  • So I have 2 solutions now? :) Can you explain me a bit more? If I figured out correctly ofstream adds std::ios::out automatically while fstream doesn't? Why does c_str() work? – Cokaric Oct 06 '13 at 10:28
  • With Op's second example I'm able to create and write to file, without `std::ios::out`, open of `fstream` has default open mode as `ios_base::in|ios_base::out` – P0W Oct 06 '13 at 10:36
  • @P0W seems I am wrong, I checked it has flag as well. I'll delete my answer – billz Oct 06 '13 at 10:38
  • @billz its okay, edit it, I guess OP used was doing some `std::string` thing – P0W Oct 06 '13 at 10:39
  • P0W and billz, Thanks I will check it out, I haven't been programming for years now. Will take some time to get back in game :) The complete code is here... http://pastebin.com/nV0TC76K @billz , your answer works fine I just don't understand it completly but I will read documentation, thank you :) – Cokaric Oct 06 '13 at 10:43