打开系统调用未按预期工作

Open system call is not working as expected

我正在尝试下面的代码。

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
    int fd;
    char filename[10];
    printf("enter the file name\n");
    scanf("%s",filename);
    fd=open(filename,O_RDONLY|O_CREAT|O_TRUNC,S_IRUSR);
    if(fd==-1)
    {
        printf("error opening file\n");
    }
    else
    {
        printf("file opened successfully\n");
    }
    return 0;
}

在这里,我设置了文件的权限,只有用户才能阅读。 当我第一次执行此代码时,它第二次作为 expected.But 显示错误 message.My 怀疑是为什么它给出错误消息,因为我已经同步设置了所需的权限模式带有标志模式。

问题在于打开标志的特定组合。你说的是:

  • 创建此文件,它不存在 (O_CREAT)
  • 截断它 (O_TRUNC)
  • 将其权限设置为 0400 (S_IRUSR)

下次当您尝试打开它时,因为它已经存在 open 将尝试截断它。但是截断会失败,因为您只有文件的读取权限。

解决此问题的一个简单方法是指定更具包容性的权限,即 0700

诊断此问题的一种简单方法(通常也是一种好的做法)是检查 errno after the system call fails. (perror, for example, will give a human-readable error message.) You would have seen the call fail with EACCES, which is documented as arising when "O_TRUNC is specified and write permission is denied."