首页 > 解决方案 > 使用绝对路径使用 ifstream 读取文件

问题描述

你好堆栈溢出社区。我作为最后的手段来到这里,因为我可能犯了一个愚蠢的错误,我看不到自己。

我问的问题是由于某种原因,当我尝试使用绝对路径(或相对路径,您可以看到我在我的代码中尝试过)时,由于某种未知原因(至少对我而言),它无法读取文件。对于我正在从事的大项目来说,这是一件小事。感谢你们!

主文件

#include <iostream>
#include <fstream>
#include <filesystem>
#include <unistd.h>
#include <string>
std::string openf() {
    FILE* pipe = popen("zenity --file-selection", "r"); // open a pipe with zenity
    if (!pipe) return "ERROR"; // if failed then return "ERROR"
    char buffer[912]; // buffer to hold data
    std::string result = ""; // result that you add too

    while(!feof(pipe)) { // while not EOF read
        if(fgets(buffer, 912, pipe) != NULL) // get path and store it into buffer
            result += buffer; // add buffer to result
    }

    //I thought i needed to convert the absolute path to relative but i did not after all
    // char cwd[10000];
    // getcwd(cwd, 10000); // get cwd(current working directory)
    // result = std::filesystem::relative(result, cwd); // convert the absolute path to relative with cwd
    pclose(pipe); // cleanup
    return result;
}

std::string readf(std::string filename){
    std::string res;
    std::ifstream file;
    file.open(filename.c_str());
    if(file.is_open()) {
        while(file){
            res += file.get();
        }
    }else {
        std::cout << "failed to open file " + filename;
    }
    return res;
}

int main( void ){
    std::string file = openf();
    std::cout << file << std::endl;
    std::string str = readf(file);
    std::cout << str << std::endl;
    return 0;
}

输出

/home/meepmorp/Code/Odin/test/test.odin

failed to open file /home/meepmorp/Code/Odin/test/test.odin

标签: c++linuxfile

解决方案


zenity您用作文件选择器的似乎在文件名之后输出了一个额外的换行符,您将其包含在名称中。在 Linux 中,文件实际上可以在其名称中包含嵌入的换行符,并且您实际上尝试打开“test.odin\n”而不是“test.odin”。


推荐阅读