C文件I/O
在C語言中,默認會打開三個輸入輸出流,分別是stdin,stdout,stderr,不難發現,這三個流的類型都是FILE*,通過fopen得到的返回值爲文件指針,指向打開的文件
#include <stdio.h>
#include <string.h>
int main(){
FILE* fp = fopen("myfile","w");
if(fp == NULL){
perror("fopen error\n");
}
const char* msg = "Hello fp\n";
int count = 5;
while(count--){
fwrite(msg,strlen(msg),1,fp);
}
fclose(fp);
return 0;
}
系統文件I/O
操作文件,當然不止有上述的C接口或者其他語言的一些接口,我們還可以通過系統所暴露的接口來進行文件訪問,例如
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(){
int fd = open("myfile",O_WRONLY|O_CREAT,0644);
if(fd < 0 ){
perror("open");
return 1;
}
int count = 5;
const char* msg = "hello fd\n";
int len = strlen(msg);
while (count--){
write(fd,msg,len);
}
close(fd);
return 0;
}
open函數:int open(const char* pathname , int flags);
int open(const char* pathname, int flags, mode_t mode);
pathname:要打開或創建的目標文件
flags: 打開文件時,可以傳入多個參數選項,用一個或多個常量進行“或”運算,構成了flag
參數:
O_RDONLY:只讀打開
O_WRONLY:只寫打開
O_RDWR :讀寫打開
上面的三個變量必須指定一個且只能指定其中一個
O_CREAT :若文件不存在,則創建它。需要使用mode選項,來指明文件的訪問權限
O_APPEND :追加寫文件
返回值:
成功:返回的事新打開的文件描述符
失敗:返回-1;
mode_t:設置權限
open函數具體使用哪一個和應用場景有關,如果目標文件不存在,需要open創建,則第三個參數表示創建函數的默認權限,否則,使用兩個參數的open。
文件描述符fd
瞭解了open函數之後,又引出了一個新的概念,文件描述符