文件IO
打开-》操作-》关闭
【1】打开文件,获取文件描述符
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
功能:打开文件,获取文件描述符
参数:pathname 文件的路径
flags O_RDONLY 只读
O_WRONLY 只写
O_RDWR 可读可写
以上三者关系:互斥
O_CREAT 如果文件不存在,创建,必须使用第三个参数
O_TRUNC 如果文件存在,清空文件的内容
O_APPEND 以追加的方式打开
O_EXCL 如果使用O_CREAT时文件已经存在,则返回错误信息,可以检测文件是否存在
返回值:成功返回文件描述符,失败返回-1
【2】权限掩码:umask
实际结果:0666 & (~umask) 系统umask是0002
【3】关闭文件
#include <unistd.h>
int close(int fd);
功能:关闭文件
参数:fd 文件描述符
返回值:成功0 失败-1
系统默认打开了三个文件描述符
0 1 2
标准输入 标准输出 标准出错
【4】读写
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
功能:从文件描述符中读
参数:fd 文件描述符
buf 读到的数据的存放位置
count 期望读到的字节数
返回值:成功读到的字节数(0代表到达文件结尾) 失败-1
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
功能:向文件描述符中写
参数:fd 文件描述符
buf 要写的内容
count 期望写的字节数
返回值:成功实际写入的字节数(0代表什么也没有写) 失败-1
练习:使用文件IO实现文件的拷贝
1.open 两个文件,注意参数
2.循环读写
3.close
【5】文件IO的偏移和定位
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
功能:文件IO的偏移和定位
参数:fd 文件描述符
offset 偏移量
whence SEEK_SET 开头位置
SEEK_CUR 当前位置
SEEK_END 结尾位置
返回值:成功返回偏移量 失败-1
【6】获取文件的信息(属性)
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);
功能:获取文件的信息
参数:path 文件的路径
buf 存放获取的信息
返回值:成功0 失败-1
stat 如果文件是链接文件,它获取的是目标文件的信息
lstat 如果文件是链接文件,它获取的是链接文件的信息
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
char *ctime(const time_t *timep);
功能:实现时间的转换
参数:时间的秒数
返回值:成功返回一个字符串,失败NULL
#include <sys/types.h>
#include <grp.h>
struct group *getgrgid(gid_t gid);
功能:通过组id获取组的信息
参数:gid 组id
返回值:成功返回信息结构体指针,失败NULL
#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwuid(uid_t uid);
功能:通过用户id获取用户信息
参数:uid 用户id
返回值:成功返回信息结构体指针,失败NULL
【7】目录相关操作
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
功能:打开一个目录,获取目录流
参数:name 目录的路径名
返回值:成功返回目录流,失败NULL
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
功能:关闭目录流
参数:dirp 要关闭的目录流
返回值:成功0 失败-1
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
功能:读目录
参数:dirp 目录流
返回值:成功返回结构体指针,失败返回NULL
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all filesystem types */
char d_name[256]; /* filename */
};