c++ - 文件存在,但打开文件仍然总是返回 -1

标签 c++

文件“~/workspace/Test.txt”确实存在,但 fd 总是返回 -1。有人可以提示代码有什么问题吗?谢谢。

 int fd = open("~/workspace/Test.txt", O_RDONLY);
 cout << "fd is "<<fd<<endl;
 if (fd < 0) {
    cout << "did not find file"<<endl;
    return false;
 }

最佳答案

(假设你的操作系统是像 Linux 这样的 Posix)

~ 应该展开。通常外壳会扩展它。但是 open 需要一个真实的文件路径。

你可以试试:

std::string fname (getenv("HOME"));
fname += "/workspace/Test.txt";
int fd = open(fname.c_str(), O_RDONLY);
if (fd<0) {
   std::cerr << "failed to open " << fname 
             << " : " << strerror(errno) << std::endl;
   return false;
}   

参见 glob(7) , wordexp(3) , getenv(3) , strerror(3) , open(2) , environ(7)

阅读Advanced Linux Programming

关于c++ - 文件存在,但打开文件仍然总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28260668/

相关文章:

c++ - 如何访问使用 omp_target_alloc() 分配的设备内存

C++ OpenGL (freeglut)

c++ - 为什么抽象类的默认析构函数不是虚拟的?

c++ - Boost::Serialization Mpi 发送用户定义类型的数组

c++ - 弃用的 OpenGL 功能

C++/带有对象指针 vector 的多个文件

c++ - 如何定义 std::ostringstream 的上限,之后所有附加数据都将被丢弃?

c++ - 视觉 C++ RECT 碰撞

c++ - python C API 是否与 C++ 完全兼容?

c++ - OpenGL 平面着色 - 奇怪的照明行为