[英]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.