Opening a file in C++ outside of the working directory
c++, file-io
Solution
Assuming you meant to use `ifstream` instead of `iostream`, your code is correct. `ifstream` can use a path to a file as well as the name of a file in the working directory.
No exceptions are thrown if the file does not exist, but the fail bit is set. You should check for this before trying to do anything with the stream.
std::ifstream input("/home/bob/stuff.txt");
if (!input) std::cerr << "Could not open the file!" << std::endl;
else
{
// ...
}
If you still cannot extract data from the file, the problem is somewhere else in your code.
Problem
I've got a program that is going to have several resource files that the user can put somewhere on the computer that isn't in the same folder as the executable. How do I get open those files? I've found lots of answers saying that the reason things aren't working is that the file isn't in the working directory. I've tried providing fully qualified paths: ``` ifstream str; str.open("/home/millere/foo.txt") ``` but that was unsuccessful. I know the path was correct (copy and paste). I can't find any documentation on it, but I assume it has to be possible. (`vim ~/foo.txt` from anywhere other than `~` works, for example).