c - Linux C,打开一个存在的文件,EEXIST错误bug

标签 c linux io errno

使用此代码,我不确定为什么在调用 open() 后出现错误(EEXIST 17 文件存在)。该文件确实存在。

int flags = O_WRONLY | O_CREAT | O_APPEND | S_IRWXU;
int fd = open("./atomic.txt", flags);

if(fd==-1)
{
    printf("error code: %d \n", errno);
    perror("open.. ");
    exit(0);
}

最佳答案

S_IRWXU模式的一部分,而不是标志:

int flags = O_WRONLY | O_CREAT | O_APPEND;
int mode = S_IRWXU;
int fd = open("./atomic.txt", flags, mode);

很可能发生的事情是 S_IRWXU 正在设置 flagsO_EXCL 位因此 open()如果文件已经存在,将失败。 确实是这样,至少在我的系统上是这样:

/usr/include/fcntl.h:
    #define S_IRWXU (__S_IREAD|__S_IWRITE|__S_IEXEC)
/usr/include/x86_64-linux-gnu/bits/stat.h:
    #define __S_IREAD  0400
    #define __S_IWRITE 0200
    #define __S_IEXEC  0100
/usr/include/asm-generic/fcntl.h:
    #define O_EXCL 00000200

可以看到__S_IWRITE模式和O_EXCL标志都是0200

关于c - Linux C,打开一个存在的文件,EEXIST错误bug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750732/

相关文章:

c - While循环变量初始化和变量类型(C)

c - C 中的 strcat() 和 fgets() 不起作用

swift - XIB View 的自动布局约束

java - 当 Java 尝试递归地遍历带有循环符号链接(symbolic link)的目录结构时,会抛出什么样的 IO 错误?

c - 如何在c中创建多个链表的数组?

c - C中如何逐行打印出一个txt文件?

html - 谷歌分析;短设置 Q

python - 无法从 Linux 机器通过 python 连接 SQL 服务器

linux - 是否可以直接从C程序或shell脚本向搜索引擎发送搜索参数?

linux - 如何根据 'sys_seek' 计算 'sys_read'?