Cannot Open Text File in Windows and Visual Studio

I am having trouble successfully opening a text file located in the same directory as the program in Windows using Visual Studio 2019. Is there a dependency for Visual Studio or Windows in the format that the text file location has to be specified? Or is there some other aspect that I am not taking into account?

Below is the code.

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
38
39
  // ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//


#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;


int main()
{
	string var;
	cout << "Hello My World!\n\n\n";

	

	ifstream datafile;

	datafile.open("RawData2.txt");

	if (datafile.is_open())
	{
		getline(datafile, var, '\n');

		while (datafile.good())
		{
			cout << var;
			getline(datafile, var);
		}

		datafile.close();
	}
}




How do you know they're in the same directory? From your app, print the directory to be sure.
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory
If you're running the program through the IDE's debugger, you need to set the working directory properly. Right click on the project in the Solution Explorer, click Properties, Debugging section, and set Working Directory to $(OutDir)
The working directory can be different depending on whether you are running your app through the VS IDE or from the directory where your .exe file resides.

Via the IDE the working directory is where your source file(s) are located.
Topic archived. No new replies allowed.