Linux的文件I/O编程
Linux的文件I/O编程
#include <fcntl.h> int open(const char *pathname, int oflag) oflag: 以下三个标志必须指定一个且只能指定一个- O_RDONLY : 只读打开
- O_WRONLY : 只写打开
- O_RDWR : 读写打开
- O_APPEND:每次写的数据都添加到文件尾
- O_TRUNC:若此文件存在,并以读写或只写打开,则文件长度为0
- O_CREAT:若文件不存在,则创建该文件。此时,open函数需要第三个参数,用于指定该文件的访问权限位(后面描述)
- O_EXCL:若同时指定了O_CREAT标志,而文件已经存在,则会出错。可用于测试文件是否存在
- F_DUPFD:类似dup2函数,复制filedes到大于等于第三参数的最小可用描述符并返回该描述符。它不是原子操作,可能被打断。
- F_GETFD:返回filedes对应的文件描述符标志(FD_CLOEXEC)。
- F_SETFD:按照第三个参数设置filedes对应的文件描述符标志。
- F_GETFL:返回filedes对应的文件状态标志(O_RDONLY、O_WRONLY、O_RDWR、O_APPEND、O_NONBLOCK、O_SYNC、OASYNC)
- F_SETFL:将第三个参数设置为文件状态标志,不能改变前三项(只读、只写、读写)。
- F_GETOWN:获取当前接收SIGIO和SIGURG信号的进程ID或进程组ID。
- F_SETOWN:将第三个参数设置为接受SIGIO和SIGURG信号的进程ID或进程组ID。若第三个参数大于0,表示进程ID;小于0则其绝对值表示一个进程组ID。
ino_t st_ino; /* inode number*/
mode_t st_mode; /* file type & mode */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
off_t st_size; /* total size, in bytes */
unsigned long st_blksize; /* blocksize */
unsigned long st_blocks; /* number of blocks allocated
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of inode last change
}; 使用如下的宏判断文件类型
普通文件 S_ISREG() 目录文件 S_ISDIR() 字符特殊文件 S_ISCHR() 块特殊文件 S_ISBLK() FIFO文件 S_ISFIFO() 套接口文件 S_ISSOCK() 符号连接 S_ISLINK()int utime(const char* pathname, const struct utimbuf *times)
修改文件的访问时间和修改时间。 struct utimbuf {
time_t actime; //访问时间
time_t modtime; //修改时间 }; int access(const char* pathname, int mode) 测试文件许可权限。成功返回0,失败返回-1。 mode取值:成功返回0,失败返回-1。 mode_t umask(mode_t cmask) 创建屏蔽字,参与指定文件的访问权限。 cmask取0即由open和creat指定权限,取(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)即禁止所有组和其他用户的访问权限。 int chmod(const char* pathname, mode_t mode) int fchmod(int filedes, mode_t mode) 修改文件存取权限。 mode取值: int chown(constchar* pathname, uid_t owner, gid_t group) 修改文件的用户ID和组ID。 int truncate(const char* pathname, off_t length) int ftruncate(int fd, off_t length) 修改文件长度。 若length小于文件长度,则超出部分消失;若length大于文件长度,则中间形成空洞,读取空洞总是得到0。
- R_OK 测试读许可权
- W_OK 测试写许可权
- X_OK 测试执行许可权
- F_OK 测试文件是否存在
评论暂时关闭