1

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Kwydin
  • 57
  • 5
  • 1
    Have you actually set `name` to a sensible value? Have you checked with the debugger? – arne Nov 26 '13 at 14:29
  • So you probably aren't reading what you think you are. Maybe spaces or what not. Use a debugger or print out what is in name. – Duck Nov 26 '13 at 14:29
  • 2
    Are you aware that filenames in Linux are case-sensitive? – Eric Finn Nov 26 '13 at 14:31
  • Everything points to `name` not having the value you expect. Have you checked, how did you check? – john Nov 26 '13 at 14:43
  • @Eric Finn yes I'm aware of that, everything is in lowercase the file name too. – Kwydin Nov 26 '13 at 15:44
  • @john @Duck in `name` I have `dane.txt` the file name and ofc I've checked it so it has just that string. So it seems to point into the right thing. And as I wrote earlier variable `name` works in windows. – Kwydin Nov 26 '13 at 15:46

1 Answers1

2

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.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Isn't `getline` in ASCII mode supposed to translate and then strip those (well, the underlying buffer does the translating)? – Lightness Races in Orbit Nov 26 '13 at 14:33
  • @LightnessRacesinOrbit: It will translate the host representation of end-of-line into `\n`. A Windows implementation will strip the `\r`, but a Linux implementation won't. – Mike Seymour Nov 26 '13 at 14:42
  • @MikeSeymour This was indeed the case. Creating new `data.dat` file in linux solved the whole problem. – Kwydin Nov 26 '13 at 16:08