繁体   English   中英

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

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

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

这是我的代码,

我正在尝试使用 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”打印到文件“output”中。 文件创建成功。 但是内容是空的

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

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

至于设备特殊文件,那些是/dev文件夹中的所有文件。 它只是一种通过正常read / write / ioctl调用与设备通信的方式。

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

注意:

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

相当于:

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

暂无
暂无

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

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