7

我一直在讨论关于 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;
}

通过检查 .txt 的值,我确认input.txt文件位于正确的“工作目录”中argv[0]。Open 方法是行不通的。

我在调试时也遇到了麻烦-我应该无法设置手表吗infile.good()infile.is_open()我不断得到

Error: member function not present.

编辑:使用 .CPP 文件中的完整代码更新代码列表。

更新:该文件不在当前工作目录中。这是项目文件所在的目录。把它移到那里,它在 VS.NET 中调试时工作。

4

5 回答 5

8

在指定打开模式时尝试使用按位或运算符。

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;
}
于 2009-04-28T16:39:16.350 回答
6

有时 Visual Studio 会将您的 exe 文件远离源代码。默认情况下,VS 可能只查找从您的 exe 文件开始的文件。此过程是从与源代码相同的目录中获取输入 txt 文件的简单步骤。如果您不想修复 IDE 设置。

using namespace std;

ifstream infile;

string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path

infile.open(path);

希望这可以帮助其他人快速解决问题。我自己花了一段时间才找到这个设置。

于 2012-11-04T12:21:07.300 回答
1

我在您的代码中发现了两个问题:

a) "ios::ate || ios::in" => 中的语法错误应该是 "ios::ate | ios::in"

b) "ios::ate" 将光标设置到文件末尾——所以当你开始阅读时你什么也得不到

所以只需删除“ios::ate”就可以了:)

乔,克里斯

于 2009-04-28T16:45:40.080 回答
0
infile.open ("input.txt", ios::ate || ios::in);

||是逻辑或运算符,而不是按位运算符(如 Bill The Lizzard 所说)。

所以我猜你正在做相当于:

infile.open ("input.txt", true);

(假设 ios::ate 或 ios::in 都不是 0)

于 2009-04-28T16:40:52.650 回答
0

尝试使用:

ifstream fStm("input.txt", ios::ate | ios::in);

我也无法调试 - 我是否应该无法在“infile.good()”或“infile.is_open()”上设置监视?我不断收到“错误:成员函数不存在”。

正确的包括:

#include <fstream> 

等等

于 2009-04-28T16:41:06.690 回答