【问题标题】:Very basic file i/o非常基本的文件 i/o
【发布时间】:2011-04-25 13:43:42
【问题描述】:

每当我尝试使用 istream 打开文件时,它都不会打开(is_open() 返回 false)。是否需要放置一个特定目录才能访问它(它在项目的输出目录中)?

ifstream ifile;
ifile.open("test.txt");
if(!ifile.is_open()){
    cout << "The file could not be opened." << endl;
}
cin.get();

【问题讨论】:

    标签: c++ file io fstream istream


    【解决方案1】:

    它需要在程序的“工作目录”中。这是您运行程序时所在的目录,或者如果您使用的是像 Visual Studio 这样的 IDE,则为项目的目录(该目录还包含 Release 和/或 Debug 构建文件夹)。

    【讨论】:

      【解决方案2】:

      您需要提供文件的正确路径。我不知道您的项目结构是什么,但类似于:

      ifile.open("output/test.txt");
      

      【讨论】:

      • 我猜到了,但是项目的基本目录是什么?
      • @猪头不知道。 C++ 没有项目的概念——这取决于你使用的是什么 IDE。
      【解决方案3】:

      我在一台 Linux 机器上工作,并且将文件 test.txt 与二进制文件放在同一目录中总是可以的。因此,如果您的项目的可执行文件名为a.out,那么以下两个步骤应该可以使其工作:

      1. 确保test.txt 与a.out 在同一目录中
      2. 在 test.txt 和 whether it exists 上检查 permissions

      【讨论】:

        【解决方案4】:

        尝试改变这一行 ifile.open("test.txt"); -> ifile.open("/test.txt");

        ifstream ifile;
        ifile.open("/test.txt");
        if(!ifile.is_open()){
            cout << "The file could not be opened." << endl;
        }
        cin.get();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-26
          • 1970-01-01
          • 2012-06-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-14
          • 2015-01-17
          相关资源
          最近更新 更多