std::ifstream::open fails when running application from inside MSVC++ 2010

I have written a program that attempts to open a file using std::ifstream::open(). open() fails when I run the program inside Visual Studio (even when I choose the option "start without debugging") but works fine if I run it outside Visual Studio. Why does this happen?

Here's some test code I wrote to isolate the problem, it runs fine outside Visual Studio and prints the file content to screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	char c;
	
	string fileName = "fileToOpen.txt";
	string fileContent;

	ifstream file;

	file.open(fileName.c_str(), ifstream::in);
	
	if(file.is_open())
		{
			cout << "File opened successfully" << endl;

			while(file.good())
			{
				file.get(c);
				fileContent.push_back(c);
			}

			cout << fileContent.c_str();
		}
	else
		cout << "File did not open successfully" << endl;
	
	file.close();
	
	cin >> c;

	return 0;
}



Thank you for any feedback, it's much appreciated.
Last edited on
It's probably that the file can't be found from the path that VS2010 runs your exe from.

Try putting the full path and filename in your code to test this.

e.g.
string fileName = "c:\\myfile\\fileToOpen.txt";
That worked Moooce, thanks a lot!

I had placed the files in the same directory as the output executable so I thought that was sufficient for VS2010 to find them.

What if I wanted to have this program work using relative paths though (and have Visual Studio be able to find the files as I work on it)? Is it a matter of specifying additional directories in the Project's properties (VC++ Directories)?

Use GetModuleFileName() API and PathRemoveFileSpec() APIs to get real executable directory.
Thank you modoran, much appreciated feedback!

Topic archived. No new replies allowed.