基于Linux做应用开发,差不多就是通过调用Linux系统提供的API实现。这些函数都可通过查询man手册找到:
man 1 file shell命令; man 2 file 查API; man 3 file 查库函数。
下面总结几个文件IO常用的API:
1、-----------open(打开文件)---------
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
参数:
pathname :文件路径名
flags :打开文件的方式
O_RDONLY, :以只读的方式打开文件
O_WRONLY, :以只写的方式打开文件
O_RDWR :以读写的方式打开文件
返回值:如果成功打开文件则返回这个文件的ID(身份证号),我们对这个号码进行操作就相当于对这个文件进行操作
如果失败返回-1。
int open(const char *pathname, int flags, mode_t mode);
参数:
pathname :文件路径名
flags :打开文件的方式
O_RDONLY, :以只读的方式打开文件
O_WRONLY, :以只写的方式打开文件
O_RDWR :以读写的方式打开文件
O_CREAT :如果文件不存在则创建
mode :创建文件是多给予的权限
返回值:如果成功打开文件则返回这个文件的ID(身份证号),我们对这个号码进行操作就相当于对这个文件进行操作
如果失败返回-1
2、--------------write(将数据写入到文件)------------
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:
fd :需要写入的文件ID
buf :写入的数据
count:写入数据的大小
返回值:如果写入数据成功则返回实际写入的数据大小
如果失败返回-1
ssize_t:其实就是用 #define 给int取一个别名,增加代码的可读性
3、-------------read-------------
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:
fd :需要读取数据的文件ID
buf:存放读取的数据
count:一次性读取的大小
返回值:如果读取数据成功则返回实际读取的数据大小
4、------------lseek-----------------
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:
fd:需要设置文件偏移量的文件ID
offset:文件偏移的大小,如果是正数代表往后偏移+5,如果是负数-5代表往前偏移
whence:文件的偏移方式
SEEK_SET:从文件头开始偏移
SEEK_CUR:从文件当前位置开始偏移
SEEK_END:从文件末尾开始偏移
5、--------------stat(获取文件的属性)--------------
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
参数:
path :需要获取文件属性所对应的文件
buf :如果成功获取将会存放到结构体
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 */
};