Reputation: 23
I am trying to open a file, but can't get it to work. The file is definitely there, in the same directory. I have tried unhiding extensions (it's definitely called test.txt and not test.txt.txt for example), and also tried using the full path. The file is not open anywhere. Any ideas?
string mostCommon(string fileName)
{
string common = "default";
ifstream inFile;
//inFile.open(fileName.c_str());
inFile.open("test.txt");
if (!inFile.fail())
{
cout << "file opened ok" << endl;
}
inFile.close();
return common;
}
Upvotes: 2
Views: 10316
Reputation: 1
Common problem might be specifying wrong path, CMakeLists.txt uses cmake-build-debug as its directory, so if your file is one level outside it, you just useprocess_file("../test.dat");
this helped me.
Upvotes: 0
Reputation: 1621
If you specify inFile.open("test.txt")
it will try to open "test.txt"
in the current working directory. Check to make certain that is actually where the file is. If you use absolute or relative pathing, make sure that you use '/'
or '\\'
as the path separator.
Here is an example that works when a file exists:
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
bool process_file(string fileName)
{
ifstream inFile(fileName.c_str());
if (!inFile)
return false;
//! Do whatever...
return true;
}
int main()
{
//! be sure to use / or \\ for directory separators.
bool opened = process_file("g:/test.dat");
assert(opened);
}
Upvotes: 2