Linux 檔案 I/O 基礎系統呼叫:open、creat、read、write、close。本文詳細說明函數原型、參數、返回值、錯誤碼、檔案描述符機制,並提供完整 C 語言範例程式 (開啟讀取、建立寫入、複製檔案)。
fork() 子進程複製父進程描述符表 (指向同一檔案表項)。
#include
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
flags (位元或組合):
返回:成功 ≥ 3 的 fd,失敗 -1 (設 errno)。
#include
int creat(const char *pathname, mode_t mode);
// 等同於 open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode)
現代建議直接用 open() 組合旗標。
#include
ssize_t read(int fd, void *buf, size_t count);
#include
ssize_t write(int fd, const void *buf, size_t count);
#include
int close(int fd);
#include
#include
#include
#include
int main() {
int fd = open("show_read.c", O_RDONLY);
if (fd == -1) { perror("open"); exit(1); }
char buf[1024];
ssize_t n = read(fd, buf, sizeof(buf));
if (n == -1) { perror("read"); exit(1); }
close(fd);
write(STDOUT_FILENO, buf, n);
return 0;
}
#include
#include
#include
int main() {
const char *msg = "Linux Programmer!\n";
int fd = open("newfile.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd == -1) return 1;
write(fd, msg, strlen(msg));
close(fd);
return 0;
}
#define BUFSZ 4096
int main(int argc, char *argv[]) {
if (argc != 3) return 1;
int src = open(argv[1], O_RDONLY);
int dst = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0644);
char buf[BUFSZ];
ssize_t n;
while ((n = read(src, buf, BUFSZ)) > 0) {
char *p = buf;
while (n > 0) {
ssize_t w = write(dst, p, n);
if (w == -1) return 1;
p += w; n -= w;
}
}
close(src); close(dst);
return 0;
}
if ((fd = open(...)) == -1) {
perror("open"); // 印出 "open: 錯誤訊息"
exit(EXIT_FAILURE);
}
搭配 errno、strerror(errno) 可自訂錯誤訊息。