Search code examples
c++linuxfilefstream

Cant open file using c_str() in linux


On Windows, I have no problems opening the file from string. On Linux (where it needs to work) I can't open the file.

    string name;

//open 1st file, with the next file name - this works
fstream file( "data.dat", ios::in);

if(file.good()){
    getline(file, name);

            //some code here

    file.close();
}else{
    return 1;
}


    // this here does not work
fstream file1(name.c_str() , ios::in);
if(file1.good()){

    //some code here

    file1.close();
}else{
    cout<<"can't open file"<<endl;
    return 1;
}

If instead name.c_str() I write the file name directly it works, but every try on getting the name from the file ended with the file not opening.

I've tried creating const char* from name, doesn't work too.


Solution

  • The file probably has Windows-style line endings. Either sanitise the file, or check for and remove any carriage-return character, \r, at the end of each line.