本文将介绍基于libfuse怎么实现一个文件的读写,以及文件读写的流程是怎样的。
1.文件写入
在代码中对一个文件进行写入数据,一般的流程是:
打开文件(open)→写入数据(write)→关闭文件(close)
其实文件系统中的操作过程跟上面的流程基本是一样的。
代码实现如下:
static int myfs_create(const char *path, mode_t mode, struct fuse_file_info *info)
{
char abpath[MAX_PATH_LEN] = {};
get_path(path, abpath);
int fd = open(abpath, O_RDWR|O_CREAT, mode);
if (fd < 0) {
return -EPERM;
}
close(fd);
return 0;
}
static int myfs_write(const char *path, const char *buf, size_t length, off_t offset, struct fuse_file_info *info)
{
char abpath[MAX_PATH_LEN] = {};
get_path(path, abpath);
int fd = open(abpath, O_RDWR, S_IRUSR|S_IWUSR);
if (fd < 0) {
return -1;
}
size_t wlen = pwrite(fd, buf, length, offset);
close(fd);
return wlen;
}
2.文件读取
在代码中对一个文件的读取的流程如下:
打开文件(open)→读取数据(read)→关闭文件(close)。
文件系统中文件的读取流程如下:
代码实现如下:
static int myfs_read(const char *path, char *buf, size_t size,
off_t offset, struct fuse_file_info *info)
{
char abpath[MAX_PATH_LEN] = {};
get_path(path, abpath);
int fd = open(abpath, O_RDONLY);
if (fd < 0) {
return -1;
}
size_t rlen = pread(fd, buf, size, offset);
close(fd);
return rlen;
}
总结
1.文件写入的时候首先会创建文件;
2.每次文件写入需要返回写入数据的长度;
3.每次文件读取需要返回读取数据的长度;
4.文件操作完成之后一定要通过close关闭文件;