Reputation: 626
I am using VS2019 and the following simple snippet of code doesn't work properly (it can't open a given file):
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::ifstream inFile("Ids.txt");
try {
inFile.exceptions(inFile.failbit);
}
catch (const std::ios_base::failure& e)
{
std::cout << "Caught an ios_base::failure.\n"
<< "Explanatory string: " << e.what() << '\n'
<< "Error code: " << e.code() << '\n';
}
if (!inFile.is_open()) {
std::cout << "Could not open a file!\n";
}
return 0;
}
I have placed Ids.txt file wherever executable is, but I am getting the following output after running a program:
Caught an ios_base::failure. Explanatory string: ios_base::failbit set: iostream stream error Error code: iostream:1 Could not open a file!
The file just contains 3 integers written line by line, but I guess it doesn't even matter, because it just can't open given file.
Upvotes: 1
Views: 3527
Reputation: 5279
When you run an executable from Visual Studio with CTRL+F5 or F5, then by default, the current working directory will be the location of the project file, not the executable file. This makes it easy to open files from where your source files are, which is practical during development.
You can also change the current working directory in the project settings (under "Debugging"). See also How do I set the working directory to the "solution directory" in c++?.
When your program is run "in the real world", the current working directory may be different, and you will want to give more thoughts to where to place data files and how to open them. This depends on what kind of application you are building, whether your data files are constant or modifiable, what purpose they serve, how large they are expected to be, etc.
Upvotes: 1