c++ - ifstream::open 在 Visual Studio Debug模式下不工作

标签 c++ visual-studio ifstream

我已经遍历了 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/

相关文章:

c++ - 使用结构体从 .txt 文件读取着色器

visual-studio - metro 应用认证

c++ - 使用 ifstream while 循环,如何显示输入错误并在下一行继续?

c++ - 从结构/类读取/写入文件

c++ - 在 C++ 中,i>-1 或 i>=0 哪个更好

c++ - 在 VS 2005 和 2010 中调试 VC6 代码时不显示大多数变量

visual-studio - Msbuild 15 包含未设置为 "do not copy"的配置文件

c++ - 具有重复输入的文件流

C++ 跳过当前 `for` 迭代的其余部分并开始一个新的迭代。

c# - Visual Studio 2017 社区版上的类图在哪里