2011-12-14 117 views
1

我试了一下creat和open系统调用。两者都以相同的方式工作,我无法预测它们之间的差异。我阅读手册页。它显示“打开可以打开设备专用文件,但创建不能创建它们”。我不明白什么是特殊文件。c中的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; 
} 

我expted内容为“你好”到文件“输出”字样。该文件已成功创建。但内容为空

回答

10

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

科瑞()等同于打开()与标志等于O_CREAT | O_WRONLY | O_TRUNC。

至于设备专用文件,这些文件夹都是/dev文件夹中的所有文件。这只是一种通过正常的拨打电话与设备进行通信的方式。

+0

感谢约阿希姆Pileborg :) – Dinesh 2011-12-14 10:06:39

0

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

需要注意的是:

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

等同于:

open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode); 
相关问题