我一直在讨论关于 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 文件中的完整代码更新代码列表。
更新: 该文件不在当前工作目录中。这是 项目文件 所在的目录。把它移到那里,它在 VS.NET 中调试时工作。
原文由 Dave Swersky 发布,翻译遵循 CC BY-SA 4.0 许可协议
在指定打开模式时尝试使用按位或运算符。
openmode 参数是位掩码。
ios::ate
用于打开文件进行追加,ios::in
用于打开文件读取输入。如果您只想读取文件,您可能只需使用:
ifstream 的默认打开模式是 ios::in,因此您现在可以完全摆脱它。以下代码使用 g++ 为我工作。