【问题标题】:C++ file won't openC++ 文件打不开
【发布时间】:2014-08-04 21:33:01
【问题描述】:

我是 C++ 新手,正在尝试打开文件,但无法正常工作。该文件肯定在那里,在同一个目录中。我尝试过取消隐藏扩展名(例如,它绝对称为 test.txt 而不是 test.txt.txt),并且还尝试使用完整路径。该文件未在任何地方打开。有什么想法(我确定这很简单,但我被卡住了)?

string mostCommon(string fileName)
{
    string common = "default";
    ifstream inFile;
    //inFile.open(fileName.c_str());
    inFile.open("test.txt");
    if (!inFile.fail())
    {
        cout << "file opened ok" << endl;
    }

    inFile.close();
    return common;
}

【问题讨论】:

  • 我认为你必须像这样指定打开模式inFile.open("test.txt", ifstream::in);
  • @Johny 模式被隐式指定为默认参数,因此没有必要,除非您希望将std::ios_base::in 与其他修饰符混合使用。
  • @SirDarius 如果您使用的是ifstream,则无论您向构造函数或open 提供什么,in 标志都会传递给basic_filebuf

标签: c++ file-io


【解决方案1】:

如果您指定inFile.open("test.txt"),它将尝试在当前工作目录中打开"test.txt"。检查以确保这实际上是文件所在的位置。如果使用绝对或相对路径,请确保使用 '/''\\' 作为路径分隔符。

这是一个在文件存在时有效的示例:

#include <fstream>
#include <string>
#include <cassert>
using namespace std;

bool process_file(string fileName)
{
    ifstream inFile(fileName.c_str());
    if (!inFile)
        return false;

    //! Do whatever...

    return true;
}

int main()
{
    //! be sure to use / or \\ for directory separators.
    bool opened = process_file("g:/test.dat");
    assert(opened);
}

【讨论】:

  • 谢谢,该文件与我的源文件在同一个位置,当我将它移到与 make 文件相同的位置时它可以工作。不确定我在指定完整路径时做错了什么,但无论如何,它现在可以工作了。
  • 这是因为您的计算机在执行您的程序时,完全不知道这个源文件是从哪里来的。一个都没有。它甚至不知道你的makefile在哪里:碰巧你正在从那个目录执行你的程序。 是当前使用的工作目录。
猜你喜欢
  • 1970-01-01
  • 2011-12-21
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多