【发布时间】:2017-12-12 20:50:52
【问题描述】:
我无法让 Visual Studio 读取文本文件。下面是我的代码。该文件在 Unix 环境中完美打开,但在复制并粘贴到 Visual Studio 时不起作用。我正在使用 fstream 打开文件。为什么文件没有被读取?
当我运行程序时,它会构建,但我没有得到任何输出。我有一个输出语句cout << "inf\n"。所以甚至没有达到循环,这就是为什么我相信文件没有被读取。同样,当我在 Unix 环境中运行相同的代码时,会显示输出语句并显示文件中的值(通过 tree.insert()、tree.remove())。
我尝试了this link 中的解决方案。正如它所建议的,我将工作目录更改为 $(ProjectDir)\Debug 和 $(ProjectDir)\Release。此外,我将文本文件从资源文件夹移动到解决方案资源管理器中的源文件夹。但是,该文件仍未被读取。
我还更新了我的代码,在 fstream inf ("BTREE5_1.txt") 之后直接包含 cerr << "Error: " << strerror(errno);。使用这行代码,我得到的输出是
Error: No such file or directory
有人能解释一下原因吗?如上所述,我的文本文件与我的代码位于同一文件夹中。
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "BTree.h"
using namespace std;
int main()
{
bool first = true;
BTree tree(6, 2);
int value;
char s[80], command;
ifstream inf("BTree5_1.txt");
cerr << "Error: " << strerror(errno);
inf.getline(s, 80);
while (inf >> command >> value)
{
cout << "inf\n";
if (command == 'i')
tree.insert(value);
else
{
if (first)
{
cout << "After all insertions.\n";
tree.print();
first = false;
} // if first
cout << "Deleting " << value << ". \n";
tree.remove(value);
tree.print();
// fgets(s, 80, stdin);
} // else deletion
} // while
system("PAUSE");
return 0;
} // main
【问题讨论】:
-
运行程序时会发生什么?
-
“麻烦”和“不起作用”与描述相反。 实际上出了什么问题?如果有的话,你会得到什么输出?您能否提供一个无效的文本文件示例?
-
请使用'strerror(errno);'检查错误代码。很可能是文件路径问题。或者,您可以通过提供完整路径而不是相对路径来验证相同。
-
您能解释一下如何检查错误代码吗?
-
请检查以下链接是否相同:stackoverflow.com/questions/17337602/…
标签: c++ visual-studio file visual-studio-2015 fstream