venerdì 23 agosto 2013

Today I evolved the "hello world" example from the fuse library (http://fuse.sourceforge.net) in order to have a minimal read-write file system. The result is the following:


#define FUSE_USE_VERSION 26

#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <stdlib.h>

static char *file_str;
static size_t len = 0;
static size_t maxlen = 1024 * 1024;
static const char *file_path = "/file";

static int file_getattr(const char *path, struct stat *stbuf)
{
int res = 0;

memset(stbuf, 0, sizeof(struct stat));
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, file_path) == 0) {
stbuf->st_mode = S_IFREG | 0644;
stbuf->st_nlink = 1;
stbuf->st_size = len;
} else
res = -ENOENT;

return res;
}

static int file_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
if (strcmp(path, "/") != 0)
return -ENOENT;

filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, file_path + 1, NULL, 0);

return 0;
}

static int file_open(const char *path, struct fuse_file_info *fi)
{
if (strcmp(path, file_path) != 0)
return -ENOENT;

return 0;
}

static int file_read(const char *path, char *buf, size_t size, off_t offset,
     struct fuse_file_info *fi)
{
if(strcmp(path, file_path) != 0)
return -ENOENT;

if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, file_str + offset, size);
} else
size = 0;

return size;
}

static int file_write(const char *path, const char *buf, size_t size,
    off_t offset, struct fuse_file_info *fi)
{
if(strcmp(path, file_path) != 0)
return -ENOENT;

if (offset < maxlen) {
if (offset + size > maxlen)
size = maxlen - offset;
memcpy(file_str + offset, buf, size);
len = fmax(offset + size,len);
} else
size = 0;

return size;
}

static int file_truncate(const char *path, off_t size)
{
if(strcmp(path, file_path) != 0)
return -ENOENT;

len = size;
return 0;
}

static struct fuse_operations file_oper = {
.getattr = file_getattr,
.readdir = file_readdir,
.open = file_open,
.read = file_read,
.write = file_write,
.truncate = file_truncate
};

int main(int argc, char *argv[])
{
file_str = malloc(maxlen);
return fuse_main(argc, argv, &file_oper, NULL);
}

Nessun commento:

Posta un commento