使用绝对路径使用ifstream发出读取文件



你好,堆栈溢出社区。我是不得已才来的,因为我可能犯了一个愚蠢的错误,我看不清自己。

我问的问题是出于某种原因,当我试图读取一个文件的绝对路径(或相对,你可以看到我在我的代码中尝试过),它不能读取文件的一些未知的原因(至少对我来说)。对于我正在做的一个大项目来说,这只是一件小事。谢谢大家!

main.cpp

#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

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

最新更新