文件IO:
C语言:文件IO
fopen(“a.txt”,“r”);---->open(“a.txt”,O_RDONLY)
C++语言:IO流
上述IO是各种高级语言为用户提供的接口
PS:高级语言实现的接口本质是调用系统接口
Linux文件IO:
1、Linux文件接口:是一个操作系统,必须为用户提供操作的接口,上面语言是调用的系统的提供的文件操作接口(底层)
2、操作步骤:
1、打开
int open(const char *pathname, int flags, mode_t mode);
形参:
pathname文件的路径
flgas:标识(可以组合)
1、只读打开O_RDONLY,不存在打开失败
2、只写打开O_WRONLY,不存在打开失败
3、创建文件:O_CREAT,不存在就创建
4、截断:O_TRUC
5、追加:O_APPEND
6、读写:O_WRRD 读写打开
mode:若创建文件时,此形参有意义,指定创建文件的权限。
返回值:
文件描述符(就数组的下标),失败:<0
2、操作
写入:
ssize_t write(int fd, const void *buf, size_t count);
形参:
fd 文件描述符
buf 写入的内容
count 写入的长度
返回值:
>=0 写入的长度
<0 写入失败
读取:
ssize_t read(int fd, void *buf, size_t count);
形参:
fd 文件描述符
buf 写入的内容
count 写入的长度
返回值:
>0 返回读取的长度
=0 读取到末尾
<0 读取失败
PS:默认打开的文件的读写位置指向开头
修改读写位置:
off_t lseek(int fd, off_t offset, int whence);
形参:
fd:文件描述符
offset:偏移量 -向前 +向后
whence:位置
SEEK_SET/SEEK_CUR/SEEK_END
3、关闭
close(int fd)
文件的属性:
系统为用户提供了stat函数来获取文件的属性
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);
形参:
path:文件路径
fd:文件描述符
buf:文件属性结构体
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* 文件和权限 */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* 用户ID */
gid_t st_gid; /* 组ID */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* 长度, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* 访问时间 */
time_t st_mtime; /* 修改 */
time_t st_ctime; /* 创建时间 */
};
st_mode:每一比特位代表不同的信息
0170000(8进制)
8进制位的高2位,代表文件的类型
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 普通文件
S_IFBLK 0060000 block device
S_IFDIR 0040000 文件夹
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
倒数第1位:其他人权限
倒数第2位:群权限
倒数第3位:创建者的权限
判断宏:
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m) socket? (Not in POSIX.1-1996.)
返回值:
成功:返回0
失败:-1
文件夹:
就是一个容器,存放子文件夹或子文件的容器
1.操作步骤:
1、打开文件夹
DIR *opendir(const char name);
形参:
name :文件夹的路径
返回值:DIR 文件夹句柄
失败:NULL
2、读取文件夹内容:
struct dirent *readdir(DIR *dirp);
返回值:
若读取到末尾(没有子文件)返回NULL
PS:打开文件夹时,指向第一个子文件;
每执行一次readdir时,就会自动指向下一个文件
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* 文件的类型*/
char d_name[256]; /* 文件名 */
};
d_type::取值范围:
DT_BLK This is a block device.
DT_CHR This is a character device.
DT_DIR This is a directory.
DT_FIFO This is a named pipe (FIFO).
DT_LNK This is a symbolic link.
DT_REG This is a regular file.
DT_SOCK This is a Unix domain socket.
DT_UNKNOWN The file type is unknown.
3、关闭文件夹
closedir(DIR);