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