【发布时间】:2021-07-27 18:46:32
【问题描述】:
你好堆栈溢出社区。我作为最后的手段来到这里,因为我可能犯了一个我看不到自己的愚蠢错误。
我问的问题是由于某种原因,当我尝试使用绝对路径(或相对路径,你可以看到我在我的代码中尝试过)它无法读取文件时出于某种未知原因(至少对我而言) .对于我正在从事的大项目来说,这是一件小事。谢谢各位!
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
【问题讨论】:
-
旁注:Why is “while ( !feof (file) )” always wrong? 您可以通过以下
if解决一些此问题,但您可以完全避免它而不是躲避它。 -
查看在打印出“打开失败”消息之前调用
perror是否会为您提供有关失败的更多信息。