C++ Trouble Reading a Text File

一曲冷凌霜 提交于 2019-12-05 21:30:16

You try to open file by name without path, this means the file shall be in current working directory of your program.

The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir). But your test file resides in resources directory. So open() function could not find it and getline() immediately fails.

Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe file is created, typically $(ProjectDir)\Debug or $(ProjectDir)\Release) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.

Another possible solution - set correct path to file in your open() call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.

Not sure if this will help but I wanted to simply open a text file for output and then read it back in. Visual Studio (2012) seems to make this difficult. My solution is demonstrated below:

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

string getFilePath(const string& fileName) {
	string path = __FILE__; //gets source code path, include file name
	path = path.substr(0, 1 + path.find_last_of('\\')); //removes file name
	path += fileName; //adds input file to path
	path = "\\" + path;
	return path;
}

void writeFile(const string& path) {
	ofstream os{ path };
	if (!os) cout << "file create error" << endl;
	for (int i = 0; i < 15; ++i) {
		os << i << endl;
	}
	os.close();
}

void readFile(const string& path) {
	ifstream is{ path };
	if (!is) cout << "file open error" << endl;
	int val = -1;
	while (is >> val) {
		cout << val << endl;
	}
	is.close();
}

int main(int argc, char* argv[]) {
	string path = getFilePath("file.txt");
	cout << "Writing file..." << endl;
	writeFile(path);
	cout << "Reading file..." << endl;
	readFile(path);
	return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!