chapter 10 System-Level I/O

Thu 8 Feb 15:43:18 GMT 2018

Part III

interaction and communication between Programs

--------------------------------------------------------

chapter 10 System-Level I/O


10.1 Unix I/O

<unistd.h> : STDIN_FILENO STDOUT_FILENO STDERR_FILENO

10.2 files

对内核而言,文本文件和二进制文件没有区别

10.3 open and close files

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(char *filename, int flags, mode_t mode);

flags:

+ O_RDONLY
+ O_WRONLY
+ O_RDWR

for write:

+ O_CREAT
+ O_TRUNC
+ O_APPEND

fd = open("foo.txt",O_WRONLY|O_APPEND,O);
umask(O_WRONLY);

#include <unistd.h>
int close(int fd);

10.4 read and write files

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t n);
ssize_t write(int fd, const void *buf,size_t n);

lseek function set position.

In the x86-64, size_t means unsigned long and ssize_t
means long type.

10.5 用RIO包健壮地读写(Robust I/O)

RIO提供两类不同函数:

+ 无缓冲的输入输出函数

对二进制读写网络有用

+ 带缓冲的输入输出函数

对文件中读写有用

10.6 读取文件元数据

应用程序能通过调用stat和fstat函数,检索到关于文件的信
息(有时也称为文件的元数据)。

10.7 读取目录内容

#include <sys/types.h>
#include <dirent.h>

+ DIR *opendir( const char *name);

+ struct dirent *readdir(DIR *dirp);

+ struct dirent {
ino_t d_ino; // inode number
char d_name[256]; // filename
};


+ int closedir(DIR *dirp);

10.8 共享文件

内核用三个相关的数据结构来表示打开的文件:

1. 描述符表(descriptor table).

Each process has its own descriptor tabel.

2. 文件表(file table).

Each file table entry consists of the current
file position, a reference count of the number
of descriptor entries that currently point to it.
The kernel will not delete the file table entry
until its reference count is Zero.

3. v-node表。

Like the file table, the v-node table is shared
by all processes. Each each contains most of the
information in the 'stat' structure, including
the st_mode and st_size members.

10.9 I/O Redirection

#include <unistd.h>
int dup2(int oldfd, int newfd);

10.10 Standard I/O

The libary(libc) provides functions for opening and
closing files( fopen and fclose ), reading and writing
bytes( fread and fwrite ), reading and writing strings
( fgets and fputs ), and sophisticated formatted I/O
( scanf and printf ).

To the programmer, a stream is a pointer to a
structure of type FILE.

10.11 综合:我该使用哪些I/O函数

posted @ 2018-03-28 23:32  孤灯下的守护者  阅读(125)  评论(0编辑  收藏  举报