PageRenderTime 31ms CodeModel.GetById 18ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/filesystems/hello/hello.c

http://macfuse.googlecode.com/
C | 83 lines | 66 code | 17 blank | 0 comment | 16 complexity | 1087fcf4cb7f4649299292839e73fa4a MD5 | raw file
 1#include <errno.h>
 2#include <fcntl.h>
 3#include <string.h>
 4#include <fuse.h>
 5
 6static const char  *file_path      = "/hello.txt";
 7static const char   file_content[] = "Hello World!\n";
 8static const size_t file_size      = sizeof(file_content)/sizeof(char) - 1;
 9
10static int
11hello_getattr(const char *path, struct stat *stbuf)
12{
13    memset(stbuf, 0, sizeof(struct stat));
14
15    if (strcmp(path, "/") == 0) { /* The root directory of our file system. */
16        stbuf->st_mode = S_IFDIR | 0755;
17        stbuf->st_nlink = 3;
18    } else if (strcmp(path, file_path) == 0) { /* The only file we have. */
19        stbuf->st_mode = S_IFREG | 0444;
20        stbuf->st_nlink = 1;
21        stbuf->st_size = file_size;
22    } else /* We reject everything else. */
23        return -ENOENT;
24
25    return 0;
26}
27
28static int
29hello_open(const char *path, struct fuse_file_info *fi)
30{
31    if (strcmp(path, file_path) != 0) /* We only recognize one file. */
32        return -ENOENT;
33
34    if ((fi->flags & O_ACCMODE) != O_RDONLY) /* Only reading allowed. */
35        return -EACCES;
36
37    return 0;
38}
39
40static int
41hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
42              off_t offset, struct fuse_file_info *fi)
43{
44    if (strcmp(path, "/") != 0) /* We only recognize the root directory. */
45        return -ENOENT;
46
47    filler(buf, ".", NULL, 0);           /* Current directory (.)  */
48    filler(buf, "..", NULL, 0);          /* Parent directory (..)  */
49    filler(buf, file_path + 1, NULL, 0); /* The only file we have. */
50
51    return 0;
52}
53
54static int
55hello_read(const char *path, char *buf, size_t size, off_t offset,
56           struct fuse_file_info *fi)
57{
58    if (strcmp(path, file_path) != 0)
59        return -ENOENT;
60
61    if (offset >= file_size) /* Trying to read past the end of file. */
62        return 0;
63
64    if (offset + size > file_size) /* Trim the read to the file size. */
65        size = file_size - offset;
66
67    memcpy(buf, file_content + offset, size); /* Provide the content. */
68
69    return size;
70}
71
72static struct fuse_operations hello_filesystem_operations = {
73    .getattr = hello_getattr, /* To provide size, permissions, etc. */
74    .open    = hello_open,    /* To enforce read-only access.       */
75    .read    = hello_read,    /* To provide file content.           */
76    .readdir = hello_readdir, /* To provide directory listing.      */
77};
78
79int
80main(int argc, char **argv)
81{
82    return fuse_main(argc, argv, &hello_filesystem_operations, NULL);
83}