The Linux Programming Interface〈檔案 I/O〉

系統呼叫

大多的 Process 可以使用以下 3 種標準file descriptor

1
2
3
0 標準輸入 stdin
1 標準輸出 stdout
2 標準錯誤 stderr

shell 一開始會將這三個一直開啟

在程式中你可以直接使用 0、1、2 表示

或是include <unistd.h> 並使用

1
2
3
STDIN_FILENO
STDOUT_FILENO
STDERR_FILENO

範例檔案如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int
main(int argc, char *argv[])
{

int inputFd, outputFd, openFlags;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];

if (argc != 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s old-file new-file\n", argv[0]);

/* Open input and output files */

inputFd = open(argv[1], O_RDONLY);
if (inputFd == -1)
errExit("opening file %s", argv[1]);

openFlags = O_CREAT | O_WRONLY | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH; /* rw-rw-rw- */
outputFd = open(argv[2], openFlags, filePerms);
if (outputFd == -1)
errExit("opening file %s", argv[2]);

/* Transfer data until we encounter end of input or an error */

while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0)
if (write(outputFd, buf, numRead) != numRead)
fatal("couldn't write whole buffer");
if (numRead == -1)
errExit("read");

if (close(inputFd) == -1)
errExit("close input");
if (close(outputFd) == -1)
errExit("close output");

exit(EXIT_SUCCESS);
}

open syscall flag 參數

1
2
3
O_RDONLY  # 唯讀
O_WRONLY # 唯寫
O_RDWE # 讀寫