문제

I have a simple data file that I want to load, in a C++ program. For weird reasons, it doesn't work:

  • I tried it on Windows assuming the file was in the same directory: failed.
  • I tried it on Windows by moving the file in C:\ directory: worked.
  • I tried it on Linux putting the file in the same directory: failed.

The snippet:

void World::loadMap(string inFileName) {
  ifstream file(inFileName.c_str(), ios::in);
  if (file) {
  }
  else 
  {
    cout<<"Error when loading the file \n";
    exit(-1);
  }
}

I call the loadMap method like this:

World::Instance()->loadMap("Map.dat");

(World is a singleton class).

How can I find the exact error, by using try-catch or anything else?

도움이 되었습니까?

해결책

The problem is the working directory.

When you specify a relative path for a file it uses the working directory (which may not be the same as the directory where you application is stored on the file system).

  • Thus you either need to use an absolute path.
  • Or you need to find the current working directory and specify the file relative to that.
  • Or change the current working directory.

다른 팁

By default, a file failing to open (or any other I/O operation) does not raise an exception. You can change this behaviour, but the standard still provides no means of extracting from an exception the exact reason for failure.

Linux filenames are case-sensitive.
Is your file actually named map.dat?

Also, did you try putting the file in the current directory?

Roger Pate's comment:

Using "./filename" (the ./ is assumed and not even required) is portable across Windows and Linux, the problem could be that the CWD isn't what he thinks it is, though.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top