【问题标题】:Having trouble opening a text file using ifstream in C++在 C++ 中使用 ifstream 打开文本文件时遇到问题
【发布时间】:2016-04-08 02:59:33
【问题描述】:

我正在开发一个文本处理器,它从文件中获取文本并将其插入到 Graph 数据结构中。我制作了图表,但我在使用文本处理器时遇到了问题。每当我执行代码时,它都会说我无法打开文件。执行代码时,我确保文本文件位于同一目录中。下面是 GraphTextProcessor 类的代码:

#include <fstream>
#include <cstring>
#include <string>
#include "Graph.h"

class GraphTextProcessor {
    private:
        Graph* m_data;

    public:
        GraphTextProcessor();
        Graph* process(std::string filename);
};

GraphTextProcessor::GraphTextProcessor() {
}

Graph* GraphTextProcessor::process(std::string filename) {
    //process text file and insert into graph here

    std::string word;

    //opens file in read mode
    std::ifstream readFile;
    readFile.open(filename.c_str(), std::ios::in);

    if (readFile.is_open()) { //Not opening
        while (readFile >> word) {
            std::cout << word << std::endl;
        }
        // Closes open text file
        readFile.close();
    }
    else {
        std::cout << "Unable to open text file." << std::endl;
    }

    return NULL;
}

我只是想先从文件中读取,然后再实际尝试写入图表。这是我在 Main 中运行的代码:

#include <iostream>
#include <string>
#include "GraphTextProcessor.h"

int main() {
    GraphTextProcessor *gp = new GraphTextProcessor();
    gp->process("hello.txt");
}

它打印"Unable to open text file"。有什么建议吗?

【问题讨论】:

  • 您可能会发现让您的"Unable to open..." 打印filename 和当前工作目录很有用,因为它将在其中查找文件。如果您从 IDE 运行程序,它可能不是您所期望的。

标签: c++ file-io ifstream


【解决方案1】:

我自己运行了代码,它运行良好。 列出您的编程环境以及您遵循的步骤。请让您的问题更详细,并准确解释您为使其工作所做的尝试。

请确保以下几点:

  1. 尝试使用完整路径名;例如,

ifstream in("C:/someDirectory/andSomeOtherDirectory/one.txt");

  1. 尝试更改文件的拼写。

例如:

"One.txt"

"ONE.txt"

  1. 您需要读取文件的权限。尝试更改文件的权限。

  2. 尝试不同的编译器

  3. 另外,如果您使用异常处理(try、throw、catch)而不是 if,那么这将有助于发现错误。

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多