This is a very odd error.
I am using Visual Studio 2012, and in a C++ project (as a container for a C project), I am loading a file in this way:
const char* fname = "SomeFile.csv";
if(!(fp = fopen(fname, "r")))
{
printf("Error! Could not open %s!\n",fname);
return;
}
The CSV is in the same folder as the .EXE, and that is the intention for this program.
1. When I run it in debug, it fails to read the CSV.
2. When I put in the full pathname to the file, it works correctly and loads the CSV.
3. When I go to the output folder in Windows Explorer, and run the .exe, it correctly loads the CSV.
4. Now here is the weird part. When I go to another folder (anywhere else), and I then paste in the full path including the .exe into Windows Explorer, it starts up the program, as it should, but it fails to read the CSV.
As a caveat, if I have the folder loaded in explorer, but run it in the VS2012 debugger, it also fails to load the CSV.
What is going on here? Why would it only find it if I am running it while the window is open in explorer?
fopen,open, etc. will, given a bare filename with no path components, attempt to open the named file in the “current directory”. Given a filename without a filesystem root it will attempt to open the file in a directory relative to the current directory. Only when given an absolute (full) path will it look exactly where you’ve told it.In a command-line based system, the current directory is pretty obvious – it’s the directory you are in when you issue the command.
In a Graphical User Interface the notion of a current directory is a bit more mushy:
WORD.EXE) and double click it – the current directory is likely to be the directory where the program is – the place to which you navigated (but there’s no standard that says this has to be the case)This last point is why you have to tell the IDE / debugger what to use as the current directory when it launches your program.
The
fileOpenDialogdoesn’t exactly “default” to the current directory – it open to where you last opened it, without changing the current directory for the program – when you pick a file it then passes the full path of that file to the program.