文件存在,但打开的文件始终返回-1 [英] File exists, but open file still always returns -1

查看:127
本文介绍了文件存在,但打开的文件始终返回-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件〜/ workspace / Test.txt确实存在,但fd总是返回-1。有人可以提供一个提示,什么是错误的代码?感谢。

File "~/workspace/Test.txt" does exist, but fd always returns -1. Can somebody please give a hint as to what is wrong with the code? Thanks.

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


推荐答案

Posix like Linux)

(Assuming your OS is some Posix like Linux)

应该扩展。通常壳膨胀它。但打开需要一个真实的文件路径。

The ~ should be expanded. Usually the shell expands it. But open wants a real file path.

您可以尝试:

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)打开(2) environ(7)

阅读高级Linux编程

这篇关于文件存在,但打开的文件始终返回-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆