打开文件给出意外的 return 值

Opening a file gives unexpected return value

谁能解释一下,为什么文件打开不成功?为什么打印 "file" 会得到 -1? char *source有问题吗?

int opf(char *source){
    int file;
    file=open(source,O_RWR);
    printf("%d",file); 
}

是否可以这样做: 文件在另一个目录中,所以

int opf(char *source){
    int file;
    file=open("some_directory/ %s",source,O_RWR);
    printf("%d",file); 
}

这里我得到 "makes integer from pointer without a cast" 错误。我尝试了很多不同的东西,但我想问题在于我没有正确掌握这些概念。

来自open()man page强调我的

Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.

因此,在您的情况下,open() 失败了。检查 errno 以获得更多详细信息。 errno 的所有可能值也记录在链接页面中。

也就是说,

  1. O_RWR 似乎不是有效的 模式 O_RDWR 是。
  2. 对于第二种方法,您可以先使用 sprintf()/snprintf() 创建 path 字符串,然后将其传递给 open().