Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't my program open a file when debugging in VS2013?

This is pretty bare-bones, meant to just get the program going so I can debug the more complex parts:

//open file
cout << "Input File Name: ";
string fileName;    
cin >> fileName;
ifstream file;  
file.open(fileName, ios_base::in);
if (!(file.good())){
    cout << "File Open Error\n";        
    return 0;
}

The program compiles fine. If I execute the debug executable from \Projects\[this project]\Debug\[program].exe by just double-clicking or browsing there via cmd, it will open the file (which is stored in that same directory) and the rest of the program hums along nicely (until it gets to the buggy parts I actually want to debug, anyways).

However, if I try to 'Start Debugging' from within VS2013, the above fails; it prints the error and immediately closes. The cmd window that the program is executing in when in debugging mode of course shows the directory in the title area, and it is definitely the same directory, but I guess it's looking for the file somewhere else. I tried copying it to the volume root as well, no joy there. I am certain this worked just fine in earlier versions of VS, but maybe I'm just brain-farting here. Any ideas?

like image 880
jmassey Avatar asked Apr 28 '14 06:04

jmassey


1 Answers

In the project properties in Visual Studio, you can set the current directory in which to start the debugged program. By default, this is set to the location of the .vcxproj file, i.e. it's not the location of the executable.

At the same time, relative paths passed to std file stream constructors are interpreted relative to the program's current directory, which is why it fails for you when debugging but not when running directly. If you instead launched the program using these cmd commands:

>cd some\random\dir
>C:\path\to\your\Projects\[this project]\Debug\[program].exe

It would fail in exactly the same way.

To modify the startup directory used by Visual Studio when debugging, go to Project > Properties > Configuration Properties > Debugging > Working Directory. Note that the setting is configuration-specific (i.e. you can have a different startup dir for each configuration). If you want to set it to the directory containing the executable, you can use the macro $(OutDir).

Perhaps preferably, you might want to move the data file into the project source directory, as it's not a build artifact.

like image 50
Angew is no longer proud of SO Avatar answered Nov 14 '22 21:11

Angew is no longer proud of SO