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