我已经遍历了 SO 上的 ifstream 问题,但我仍然无法阅读简单的文本文件。我正在使用 Visual Studio 2008。
这是我的代码:
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("input.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
_getch();
return 0;
}
我已通过检查 argv[0]
的值确认 input.txt 文件位于正确的“工作目录”中。 Open 方法将不起作用。
我在调试时也遇到了问题 - 我是否应该无法在 infile.good()
或 infile.is_open()
上设置监视?我不断得到
Error: member function not present.
编辑:使用 .CPP 文件中的完整代码更新了代码 list 。
更新:该文件不在当前工作目录中。这是项目文件 所在的目录。将它移到那里,在 VS.NET 中调试时它可以工作。
最佳答案
在指定打开方式时尝试使用按位或运算符。
infile.open ("input.txt", ios::ate | ios::in);
openmode参数是位掩码。 ios::ate
用于打开文件追加,ios::in
用于打开文件读取输入。
如果你只想读取文件,你可以只使用:
infile.open ("input.txt", ios::in);
ifstream 的默认打开模式是 ios::in,因此您现在可以完全摆脱它。以下代码使用 g++ 为我工作。
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
ifstream infile;
infile.open ("input.txt");
if (infile)
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
getchar();
return 0;
}
关于c++ - ifstream::open 在 Visual Studio Debug模式下不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/798798/