2011-12-14 53 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); 
相關問題