核心系統調用
| 函數 | 原型 | 說明 |
| open | int open(const char *path, int flags, mode_t mode); | 打開/創建文件,返回文件描述符 fd |
| read | ssize_t read(int fd, void *buf, size_t count); | 從 fd 讀最多 count 字節到 buf,返回實際讀取字節數 |
| write | ssize_t write(int fd, const void *buf, size_t count); | 向 fd 寫入 buf 前 count 字節,返回實際寫入字節數 |
| close | int close(int fd); | 關閉文件描述符 |
| fsync | int fsync(int fd); | 強制將緩沖區數據刷入磁盤 |
常用 open flags 組合
O_RDONLY、O_WRONLY、O_RDWR:讀寫模式(三選一)
O_CREAT:不存在則創建,需配合 mode(如 0644)
O_TRUNC:截斷為 0 長度
O_APPEND:追加寫入
寫入示例
#include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h>
int main() {
int fd = open("txt1.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) { perror("open"); return 1; }
char *s = "hello ...";
write(fd, s, strlen(s));
fsync(fd); // 確保落盤
close(fd);
return 0;
}
讀取示例
int fd = open("txt1.txt", O_RDONLY);
if (fd == -1) { perror("open"); return 1; }
char buf[100];
ssize_t n = read(fd, buf, sizeof(buf)-1);
if (n > 0) { buf[n] = '\0'; printf("%s\n", buf); }
close(fd);
關鍵區別:緩衝 I/O vs 系統調用
fopen/fread/fwrite:標準庫用戶態緩衝,性能高、可移植、支持格式化。
open/read/write:內核態直接調用,無用戶態緩衝、原子操作、適用底層/高併發/精確控制場景。
- 混用同一 fd 會導致數據錯亂,嚴禁混用。
錯誤處理模式
if (fd == -1) {
fprintf(stderr, "open failed: %s\n", strerror(errno));
return 1;
}