Merge remote-tracking branch 'origin/fuse_2_9_bugfix'
[fuse.git] / example / hello.c
blobd26d826cdb89050e2c99b0cf5eaa95344c48f88e
1 /*
2 FUSE: Filesystem in Userspace
3 Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
5 This program can be distributed under the terms of the GNU GPL.
6 See the file COPYING.
7 */
9 /** @file
11 * hello.c - minimal FUSE example featuring fuse_main usage
13 * \section section_compile compiling this example
15 * gcc -Wall hello.c `pkg-config fuse3 --cflags --libs` -o hello
17 * \section section_usage usage
18 \verbatim
19 % mkdir mnt
20 % ./hello mnt # program will vanish into the background
21 % ls -la mnt
22 total 4
23 drwxr-xr-x 2 root root 0 Jan 1 1970 ./
24 drwxrwx--- 1 root vboxsf 4096 Jun 16 23:12 ../
25 -r--r--r-- 1 root root 13 Jan 1 1970 hello
26 % cat mnt/hello
27 Hello World!
28 % fusermount -u mnt
29 \endverbatim
31 * \section section_source the complete source
32 * \include hello.c
36 #define FUSE_USE_VERSION 30
38 #include <config.h>
40 #include <fuse.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <fcntl.h>
46 static const char *hello_str = "Hello World!\n";
47 static const char *hello_path = "/hello";
49 static int hello_getattr(const char *path, struct stat *stbuf)
51 int res = 0;
53 memset(stbuf, 0, sizeof(struct stat));
54 if (strcmp(path, "/") == 0) {
55 stbuf->st_mode = S_IFDIR | 0755;
56 stbuf->st_nlink = 2;
57 } else if (strcmp(path, hello_path) == 0) {
58 stbuf->st_mode = S_IFREG | 0444;
59 stbuf->st_nlink = 1;
60 stbuf->st_size = strlen(hello_str);
61 } else
62 res = -ENOENT;
64 return res;
67 static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
68 off_t offset, struct fuse_file_info *fi)
70 (void) offset;
71 (void) fi;
73 if (strcmp(path, "/") != 0)
74 return -ENOENT;
76 filler(buf, ".", NULL, 0);
77 filler(buf, "..", NULL, 0);
78 filler(buf, hello_path + 1, NULL, 0);
80 return 0;
83 static int hello_open(const char *path, struct fuse_file_info *fi)
85 if (strcmp(path, hello_path) != 0)
86 return -ENOENT;
88 if ((fi->flags & 3) != O_RDONLY)
89 return -EACCES;
91 return 0;
94 static int hello_read(const char *path, char *buf, size_t size, off_t offset,
95 struct fuse_file_info *fi)
97 size_t len;
98 (void) fi;
99 if(strcmp(path, hello_path) != 0)
100 return -ENOENT;
102 len = strlen(hello_str);
103 if (offset < len) {
104 if (offset + size > len)
105 size = len - offset;
106 memcpy(buf, hello_str + offset, size);
107 } else
108 size = 0;
110 return size;
113 static struct fuse_operations hello_oper = {
114 .getattr = hello_getattr,
115 .readdir = hello_readdir,
116 .open = hello_open,
117 .read = hello_read,
120 int main(int argc, char *argv[])
122 return fuse_main(argc, argv, &hello_oper, NULL);