Linux學習筆記-Linux下讀寫檔案
阿新 • • 發佈:2018-12-07
在Linux程式設計需要讀寫檔案時,有兩種方式:
(1)ANSIC: 使用stdio.h裡的函式。fopen, fclose, fwrite, fread
(2)Linux API:Linux提供了另外一套API用於操作檔案。open, close, write, read
ANSI C優點:被各平臺都支援,因此一份程式碼可以適用多種平臺。
ANSIC函式:
(1)檔案路徑: 使用/
(2)文字檔案時,換行符有區別
windows: \r\n
linux: \n
注:換行符是一個約定俗成的東西
Linux API檔案操作
以下三者選一:
O_RDONLY 只讀方式
O_WRONLY 以只寫方式開啟檔案
O_RDWR 以可讀寫方式開啟檔案
額外的標識位:
O_CREAT可與O_WRONLY聯用,若欲開啟的檔案不存在則自
動建立該檔案
O_TRUNC 可與O_WRONLY聯用,在開啟檔案時清空檔案
O_APPEND可與O_WRONLY聯用,表示追加內容
O_NONBLOCK 表示以“非阻塞”方式讀/寫資料時
過程如下:
當前檔案和路徑如下:
使用ANSIC函式
#include <stdio.h> #include <string.h> int main(){ FILE *fp = fopen("/root/CDemo/CFile/a.txt", "wb"); if(!fp){ printf("open failed!\n"); return -1; } char buf[] = "hello\nworld\n"; fwrite(buf, 1, strlen(buf), fp); fclose(fp); return 0; }
執行截圖如下:
使用Linux API
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd = open("/root/CDemo/CFile/b.txt", O_WRONLY | O_CREAT, 0644);
if(fd < 0){
printf("open failed!\n");
return -1;
}
char data[12] = "Linux";
write(fd, data, 5);
close(fd);
return 0;
}
讀取檔案:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd = open("/root/CDemo/CFile/a.txt", O_RDONLY);
if(fd < 0){
printf("open failed!\n");
return -1;
}
char data[128];
int n = read(fd, data, 128);
if(n > 0){
data[n] = 0;
printf("read:%s \n", data);
}
close(fd);
return 0;
}
執行截圖如下: