The following code:
char filename[64];
ifstream input;
cout << "Please enter the filename: " << endl;
cin >> filename;
input.open(filename);
if (!input.is_open())
{
cout << "Opening file " << filename << " failed." << endl;
exit(1);
}
fails, it enters the if() and exits. What could possibly be the cause for this? I’m using Microsoft Visual C++. When I hardcoded the filename as a constant it instead ended up garbled:
http://pici.se/pictures/CNQEnwhgo.png
Suggestions?
[Edit]
I managed to condense it into this minimal test case that fails:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]){
ifstream input;
input.open("C:\\test.txt");
if (!input.is_open())
{
cout << "Failed." << endl;
exit(1);
}
return 0;
}
I was wondering if there might be some discrepancy with the keymaps? That I’m inputting the filename in some charset while the filesystem knows it under some other name? I’m using Windows, by the way.
[Edit] Thanks for all your help but I give up now. I’ll use C style fopen instead. 🙂
[Edit] Oh my god. Now I feel so stupid. Turns out the file was actually named test.txt.txt and Windows hid the second .txt Once again, thanks for all your help…
Can you make sure that the filename is what you think it is?
On Unix/Linux systems, remember that file names are case sensitive.
Are two distinct and separate files.
[EDIT]
ifstream::open is defined as:
Try changing “C:\test.txt” to simply “test.txt” and run this program from the “C:\” directory.
Here is an exact similar sample:
If something this obvious isn’t working, it’s time to fire up the debugger.