首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Linux C 文件讀寫系統調用詳解:read/write/open/close/sync 完整實戰

     編輯:關於C語言

核心系統調用

函數原型說明
openint open(const char *path, int flags, mode_t mode);打開/創建文件,返回文件描述符 fd
readssize_t read(int fd, void *buf, size_t count);從 fd 讀最多 count 字節到 buf,返回實際讀取字節數
writessize_t write(int fd, const void *buf, size_t count);向 fd 寫入 buf 前 count 字節,返回實際寫入字節數
closeint close(int fd);關閉文件描述符
fsyncint 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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved