【问题标题】:What is the difference between open and creat system call in c?c中的open和creat系统调用有什么区别?
【发布时间】:2012-01-20 01:57:13
【问题描述】:

我尝试了 creat 和 open 系统调用。两者都以相同的方式工作,我无法预测它们之间的区别。我阅读了手册页。它显示“Open 可以打开设备特殊文件,但 creat 不能创建它们”。我不明白什么是特殊文件。

这是我的代码,

我正在尝试使用 creat 系统调用来读取/写入文件。

#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<stdlib.h>
int main()
{
 int fd;
 int written;
 int bytes_read;
 char buf[]="Hello! Everybody";
 char out[10];
 printf("Buffer String : %s\n",buf);
 fd=creat("output",S_IRWXU);
 if( -1 == fd)
 {
  perror("\nError opening output file");
  exit(0);
 }

 written=write(fd,buf,5);
 if( -1 == written)
 {
  perror("\nFile Write Error");
  exit(0);
 }
 close(fd);
 fd=creat("output",S_IRWXU);

 if( -1 == fd)
 {
  perror("\nfile read error\n");
  exit(0);
 }
 bytes_read=read(fd,out,20);
 printf("\n-->%s\n",out);
 return 0;
}

我将内容“Hello”扩展为打印在“输出”文件中。文件创建成功。但是内容是空的

【问题讨论】:

    标签: c unix file-io


    【解决方案1】:

    creat 函数创建文件,但无法打开现有文件。如果在现有文件上使用creat,该文件将被截断并且只能写入。引用Linux manual page

    creat() 等价于open(),其标志等于O_CREAT|O_WRONLY|O_TRUNC

    设备专用文件,都是/dev文件夹下的文件。这只是一种通过普通的read/write/ioctl 调用与设备进行通信的方式。

    【讨论】:

      【解决方案2】:

      在早期版本的 UNIX 系统中,open 的第二个参数只能是 0、1 或 2。无法打开不存在的文件。因此,需要一个单独的系统调用 creat 来创建新文件。

      注意:

      int creat(const char *pathname, mode_t mode);
      

      相当于:

      open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode);
      

      【讨论】:

        猜你喜欢
        • 2010-10-09
        • 2015-07-01
        • 2012-01-13
        • 1970-01-01
        • 2016-02-12
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多