C++读取文本文件出现问题

4
我在尝试读取一个文本文件,但是没有任何输出。我觉得可能是它没有正确地链接到我的Visual Studio资源文件夹,但如果我双击它,它可以在Visual Studio中正常打开,并且如果我测试它是否打开或是否好,它不会遇到任何问题。目前程序编译良好,但没有输出。我的命令提示符上面没有任何内容打印出来。有什么建议吗?
代码:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
    char str[100];
    ifstream test;
    test.open("test.txt");

    while(test.getline(str, 100, '#'))
    {
        cout << str << endl;
    }

    test.close();
    return 0;
}

文本文件

This is a test Textfile#Read more lines here#and here

1
你知道文件是否能够顺利打开吗?你应该检查返回值。 - Dabbler
也许你只需要在VS IDE中在return 0;语句上设置一个断点以查看一些输出,或者在return 0;之前添加类似于system("PAUSE");cin.get()的内容。 - Mr.C64
有点不相关,但为什么要使用C字符串?std::string更安全。string str; while (getline(test, str, '#')) {} - Geoff Montee
可以在VS2010命令行中工作。 - Mr.C64
@NateKohl 你说得对,如果我删除 text.txt 文件,它仍然会打开它吗?我的 text.txt 文件与我的解决方案在同一个文件夹中。 - Howdy_McGee
显示剩余4条评论
2个回答

10

如果你尝试通过文件名打开文件而没有指定路径,这意味着该文件应该在程序的当前工作目录下。

问题出在当你从VS IDE运行程序时的当前目录。默认情况下,VS会将程序运行的当前工作目录设置为项目目录$(ProjectDir)。但是你的测试文件位于资源目录中,因此open()函数找不到它,并且getline()函数会立即失败。

解决方案很简单-将你的测试文件复制到项目目录中,或者将其复制到目标目录(生成的程序.exe文件所在的目录,通常是$(ProjectDir)\Debug$(ProjectDir)\Release),并在VS IDE中更改工作目录设置:Project->Properties->Debugging->Working Directory,设置为$(TargetDir)。这样,在IDE和命令行/Windows资源管理器中都可以正常工作。

另一个可能的解决方案是在open()调用中设置正确的文件路径。为了测试/教育目的,你可以硬编码它,但实际上这不是良好的软件开发风格。


1

不确定这是否有帮助,但我想简单地打开一个文本文件进行输出,然后将其读回。Visual Studio(2012)似乎使这变得困难。我的解决方案如下所示:

#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;
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接