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

Din*_*esh 1 c unix file-io

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

这是我的代码,

我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)

我在"输出"文件中打印了内容"Hello".文件已成功创建.但内容是空的

Som*_*ude 13

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

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

对于设备专用文件,这些是文件creat()夹中的所有文件.它只是通过普通open()/ O_CREAT|O_WRONLY|O_TRUNC/ /dev呼叫与设备通信的一种方式.