简体   繁体   English

c 中的 open 和 creat 系统调用有什么区别?

[英]What is the difference between open and creat system call in c?

I tried both creat and open system call.我尝试了 creat 和 open 系统调用。 Both working in the same way and I can't predict the difference among them.两者都以相同的方式工作,我无法预测它们之间的差异。 I read the man page.我阅读了手册页。 It shows "Open can open device special files, but creat cannot create them".它显示“打开可以打开设备特殊文件,但创建不能创建它们”。 I dont understand what is a special file.我不明白什么是特殊文件。

Here is my code,这是我的代码,

I am trying to read/write the file using creat system call.我正在尝试使用 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;
}

I expted the content "Hello" to printed in the file "output".我将内容“Hello”打印到文件“output”中。 The file created successfully.文件创建成功。 But content is empty但是内容是空的

The creat function creates files, but can not open existing file. creat函数创建文件,但不能打开现有文件。 If using creat on an existing file, the file will be truncated and can only be written to.如果在现有文件上使用creat ,该文件将被截断并且只能写入。 To quote from the Linux manual page :引用Linux 手册页

creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC . creat()等价于open()标志等于O_CREAT|O_WRONLY|O_TRUNC

As for device special files, those are all the files in the /dev folder.至于设备特殊文件,那些是/dev文件夹中的所有文件。 It's simply a way of communicating with a device through normal read / write / ioctl calls.它只是一种通过正常read / write / ioctl调用与设备通信的方式。

In early versions of the UNIX System, the second argument to open could be only 0, 1, or 2. There was no way to open a file that didn't already exist.在 UNIX 系统的早期版本中,open 的第二个参数只能是 0、1 或 2。无法打开不存在的文件。 Therefore, a separate system call, creat, was needed to create new files.因此,需要一个单独的系统调用 creat 来创建新文件。

Note that:注意:

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

is equivalent to:相当于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM