ifstream::open 在 Visual Studio 调试模式下不起作用

新手上路,请多包涵

我一直在讨论关于 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 许可协议

阅读 755
1 个回答

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

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

原文由 Bill the Lizard 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题