tags:

views:

124

answers:

4

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?

+2  A: 

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.

anon
Prasoon: in the future, probably a good idea to wait until the post is 5 mintues old before editing for that---let the author have a window to find those errors himself, and 5 mins corresponds to what SO recognizes as "the same edit".
Roger Pate
@Roger I don't mind people fixing my typos - I'm a pretty crap typist. I agree in general with you, though.
anon
+1  A: 

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

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

SLaks
The file is Map.dat. And yes it's in the current directory !
Amokrane
+1  A: 

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.

Amokrane
+2  A: 

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.
Martin York