c++ - 使用绝对路径使用 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
解决方案
zenity
您用作文件选择器的似乎在文件名之后输出了一个额外的换行符,您将其包含在名称中。在 Linux 中,文件实际上可以在其名称中包含嵌入的换行符,并且您实际上尝试打开“test.odin\n”而不是“test.odin”。
推荐阅读
- c# - 替换角色上的精灵图像
- multithreading - 如何使用 CLI 工具确定 Wildfly 11 上哪些线程正在使用大量 CPU?
- java - 在 VS Code 中用 Java 创建控制台应用程序
- algorithm - 具有正和 <= K 的最小长度子序列
- c# - 如何查看是否在另一个表单上选中了复选框?
- python - sklearn中权重设置为距离的KNN
- android - 方法 onCreate(Bundle) 已在 MainActivity 类中定义
- kubernetes - Pod 连接失败 - 从 pod 获取响应时操作超时
- sql - 访问 VBA DlookUp 查询 SQL
- mysql - 如何在 bash 脚本中捕获 mysqldump 错误?