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 系統呼叫完整指南

編輯:Linux 教學

路徑分隔符記憶法

Linux 用 /,Windows 用 \。\ 與 W 形狀相似 → Windows;Linux 是反方向,好記。

核心系統呼叫

1. open():開啟檔案 → 取得檔案描述符

#include <sys/types.h>, <sys/stat.h>, <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
  • flags:O_RDONLY、O_WRONLY、O_RDWR、O_CREAT、O_TRUNC、O_APPEND 等組合。
  • 回傳:-1 失敗;≥0 檔案描述符(0=stdin, 1=stdout, 2=stderr,進程分配從 3 起)。
  • 同一檔案多次開啟,各得不同描述符;多進程可同時開啟同一檔案。

2. read():讀取資料到緩衝區

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
  • 回傳實際讀取位元組數;遇 EOF 回 0;錯誤回 -1。
  • 若檔案剩餘位元組 < count,僅讀取剩餘量並回傳實際數。

3. write():將緩衝區資料寫入檔案

size_t write(int fd, const void *buf, size_t count);
  • 回傳實際寫入位元組數;可能因檔案大小限制或磁碟空間不足而 < count,必須檢查回傳值。

4. close():關閉檔案描述符

int close(int fd);
  • 釋放描述符,使其可重用。成功回傳 0,失敗 -1。

5. creat():建立/截斷檔案(舊式,等同 open(..., O_CREAT|O_TRUNC|O_WRONLY))

int creat(const char *pathname, mode_t mode);
  • 回傳檔案描述符,僅可寫入。

實戰範例

讀取檔案並印出

#include <unistd.h>, <fcntl.h>, <stdio.h>, <stdlib.h>
int main() {
    int fd = open("show_read.c", O_RDONLY);
    char buf[1024];
    int n = read(fd, buf, sizeof(buf));
    close(fd);
    write(STDOUT_FILENO, buf, n);
    return 0;
}

建立新檔、寫入、讀回驗證

int main() {
    char *s = "Linux Programmer!\n";
    char buf[1024];
    int fd = creat("newfile.txt", 0644);      // 建立/清空
    fd = open("newfile.txt", O_WRONLY);       // 重開以寫入
    write(fd, s, strlen(s));
    close(fd);

    fd = open("newfile.txt", O_RDONLY);
    int n = read(fd, buf, sizeof(buf));
    close(fd);
    write(STDOUT_FILENO, buf, n);
    return 0;
}

自製 cp 指令核心邏輯

while ((n = read(src_fd, buf, BUFSIZ)) > 0)
    write(dst_fd, buf, n);

搭配 open 來源 O_RDONLY、目的 O_WRONLY|O_CREAT|O_TRUNC 即可實現基本複製。

Copyright © Windows教程網 All Rights Reserved