Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 標準 I/O 與系統 I/O 函式庫完整對照表

編輯:Linux 教學

Linux 程式開發中,標準 I/O (ANSI C 標準庫) 與系統 I/O (POSIX 系統呼叫) 是檔案操作的兩大體系。本文整理兩者核心函式原型、回傳值、錯誤處理與適用場景對照。

一、標準 I/O 函式 (stdio.h)

特點: 帶緩衝、可移植、高層介面、支援格式化輸入輸出

函式原型回傳值 (成功)回傳值 (失敗)說明
fopenFILE *fopen(const char *pathname, const char *mode);檔案指標 FILE*NULL開啟檔案,mode: r/w/a/r+/w+/a+
fcloseint fclose(FILE *fp);0EOF關閉檔案流,刷新緩衝區
fgetcint fgetc(FILE *fp);讀取的字元 (unsigned char)EOF讀取單一字元
fputcint fputc(int c, FILE *fp);寫入的字元EOF寫入單一字元
fgetschar *fgets(char *buf, int n, FILE *fp);buf 指標NULL讀取一行 (含換行符),最多 n-1 字元
fputsint fputs(const char *str, FILE *fp);非負值EOF寫入字串 (不含結束符)
freadsize_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp);成功讀取的項目數0 (或 < nmemb)二進制區塊讀取
fwritesize_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp);成功寫入的項目數0 (或 < nmemb)二進制區塊寫入
fseekint fseek(FILE *fp, long offset, int whence);0-1移動檔案位置指標
ftelllong ftell(FILE *fp);目前位移量-1取得目前檔案位置
rewindvoid rewind(FILE *fp);無無位置歸零
fflushint fflush(FILE *fp);0EOF強制刷新輸出緩衝區

二、系統 I/O 函式 (unistd.h / fcntl.h)

特點: 無緩衝 (直接系統呼叫)、低層介面、檔案描述子 (fd)、效能高、適合二進制/大量資料

函式原型回傳值 (成功)回傳值 (失敗)說明
openint open(const char *pathname, int flags, mode_t mode);檔案描述子 fd (>=0)-1開啟/建立檔案,flags: O_RDONLY/O_WRONLY/O_RDWR/O_CREAT/O_TRUNC/O_APPEND
closeint close(int fd);0-1關閉檔案描述子
readssize_t read(int fd, void *buf, size_t count);讀取位元組數-1讀取資料到緩衝區
writessize_t write(int fd, const void *buf, size_t count);寫入位元組數-1從緩衝區寫入資料
lseekoff_t lseek(int fd, off_t offset, int whence);新位移量-1移動讀寫位置,whence: SEEK_SET/SEEK_CUR/SEEK_END
statint stat(const char *pathname, struct stat *buf);0-1取得檔案狀態資訊
fcntlint fcntl(int fd, int cmd, ...);視 cmd 而定-1檔案控制 (鎖定、非阻塞、關閉執行旗標等)
ioctlint ioctl(int fd, unsigned long request, ...);0-1裝置控制 (終端機、網路介面等)

三、核心差異與選擇指南

維度標準 I/O (FILE*)系統 I/O (fd)
緩衝機制全緩衝/行緩衝/無緩衝 (自動)無緩衝 (直接進核心)
可移植性高 (ANSI C 標準)POSIX 相容系統
格式化 I/O支援 (fprintf, fscanf)不支援 (需自行格式化)
效能中等 (用戶空間緩衝)高 (避免複製,適合大檔)
檔案鎖定flockfile/funlockfilefcntl/flock (更精細)
適用場景文字處理、格式化輸出、一般應用二進制檔案、高效能、網路程式、裝置驅動

四、轉換與互操作

#include 
#include 

FILE *fp = fopen("file.txt", "r");
int fd = fileno(fp);        // FILE* → fd
FILE *fp2 = fdopen(fd, "r"); // fd → FILE* (需注意緩衝區同步)

五、錯誤處理最佳實務

// 標準 I/O
FILE *fp = fopen("data.bin", "rb");
if (!fp) {
    perror("fopen failed");
    exit(EXIT_FAILURE);
}

// 系統 I/O
int fd = open("data.bin", O_RDONLY);
if (fd == -1) {
    perror("open failed");
    exit(EXIT_FAILURE);
}

// 統一使用 errno 檢查具體錯誤原因
#include 
#include 
if (errno == ENOENT) { /* 檔案不存在 */ }
if (errno == EACCES) { /* 權限不足 */ }
Copyright © Windows教程網 All Rights Reserved