gpt4 book ai didi

c - 打开文件给出意外的返回值

转载 作者:行者123 更新时间:2023-11-30 20:44:47 25 4
gpt4 key购买 nike

有人可以解释一下为什么文件打开不成功吗?为什么打印“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);
}

这里我得到“从指针生成整数而不进行强制转换”错误。我尝试了很多不同的事情,但我想问题在于我没有正确掌握这些概念。

最佳答案

来自man page open()(强调我的)

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()

关于c - 打开文件给出意外的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37181924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com