文件I0

UNIX 环境高级编程第三章
本章描述了 UNIX 文件I/O的知识

打开一个文件或设备

1
2
3
4
5
6
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags, mode_t mode);
int openat(int fd, const char *pathname, int flags, mode_t mode);

flags:
O_RDONLY, O_WRONLY, O_RDWR 个有且有一个
可选:
O_APPEND 每次写时都追加到文件的尾端
O_CREAT 若此文件不存在则创建它
O_TRUNC 若此文件存在,而且为只写或读-写成功打开,则将其长度截取为0
O_SYNC 等待写完成(数据和属性)

fd 参数把 open 和 openat 函数区分开来,共有三种可能性。
1). path 参数指定的绝对路径名,在这种情况下,fd 参数被忽略,openat 函数相当于open函数。
2). path 参数指定的是相对路径名,fd 参数指出了相对路径名在文件系统中的开始地址。fd参数是通过打开相对路径名所在的目录来获取。
3). path 参数指定了相对路径名,fd 参数具有特殊值 AT_FDCWD。在这种情况下,路径名在当前工作中获取,openat 函数在操作上与 open 函数类似。

创建一个新文件

1
2
3
#include <fcntl.h>

int creat(const char *path, mode_t mode);

Note:
此函数等价于:
open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);

关闭一个打开的文件

1
2
3
#include <unistd.h>

int close(int fd);

设置文件偏移量

1
2
3
#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

对参数 offset 的解释与参数 whence 有关
1). 若 whence 是 SEEK_SET, 则将该文件的偏移量设置为距文件开始处 offset 个字节
2). 若 whence 是 SEEK_CUR, 则将该文件的偏移量设置为其当前值加 offset,offset 可为正或负
3). 若 whence 是 SEEK_END, 则将该文件的偏移量设置为文件长度加 offset,offset 可正可负
若 lseek 成功执行,则返回新的文件偏移量。
如果文件描述符指向的是一个管道,FIFO 或网络套接字,则 lseek 返回-1,并将 errno 设置为 ESPIPE
lseek – l 指的是 long (长整型)

读取数据

1
2
3
#include <unistd.h>

ssize_t read(int fd, void *buf, size_t nbytes);

返回值:
1). 若读取成功则返回读到的字节数
2). 若已到文件尾,返回0
3). 若出错,返回-1

写数据

1
2
3
#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t nbytes);

返回值:
1). 若写入失败则返回已写的字节数
2). 若出错,返回-1

原子读写操作

1
2
3
4
5
#include <unistd.h>

ssize_t pread(int fd, void *buf, size_t nbytes, off_t offset);

ssize_t pwrite(int fd, const void *buf, size_t nbytes, off_t offset);

返回值:
与 open, write 系统调用的返回值相同

函数 dup 和 dup2

1
2
3
4
5
#include <unistd.h>

int dup(int oldfd);

int dup2(int oldfd, int newfd);

返回值:
1). 若成功,则返回新的文件描述符
2). 若出错,返回-1

函数 sync, fsync, fdatasync

1
2
3
4
5
6
7
#include <unistd.h>

int fsync(int fd);

int fdatasync(int fd);

void sync(void);

返回值(fsync, fdatasync):
1). 若成功,返回0
2). 若出错,返回-1

函数 fcntl

1
2
3
#include <fcntl.h>

int fcntl(int fd, int cmd, ... /* int arg */);

返回值:
1). 若成功,则依赖于 cmd
2). 若出错,返回-1
fcntl 函数有以下5种功能:
1). 复制一个已有的描述符(cmd = F_DUPFD 或 F_DUPFD_CLOEXEC)
2). 获取/设置文件描述符标志(cmd = F_GETFD 或 F_SETFD)
3). 获取/设置文件状态标志(cmd = F_GETFL 或 F_SETFL)
4). 获取/设置异步 I/O 所有权(cmd = F_GETOWN 或 F_SETOWN)
5). 获取/设置记录锁(cmd = F_GETLK, F_SETLK 或 F_SETLKW)

函数 ioctl

1
2
3
#include <sys/ioctl.h>

int ioctl(int fd, unsigned long request, ...);

返回值:
1). 若出错,返回-1
2). 若成功,返回其他值

# UNIX

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×