fopen_cornercases.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include <sys/types.h>
  8. #include <unistd.h>
  9. #define FILENAME_MAX_LENGTH 255
  10. #define PATH "tmp/"
  11. #define MSG "Hello World"
  12. int main(int argc, char** argv) {
  13. size_t rets;
  14. int reti;
  15. char filename[FILENAME_MAX_LENGTH];
  16. memset(filename, 'a', sizeof(filename));
  17. filename[FILENAME_MAX_LENGTH - 1] = '\0';
  18. char filepath[sizeof(PATH) + sizeof(filename) - 1];
  19. strcpy(filepath, PATH);
  20. strcat(filepath, filename);
  21. printf("filepath = %s (len = %lu)\n", filepath, strlen(filepath));
  22. /* sanity check: try fopening empty filename (must fail) */
  23. FILE* fp = fopen("", "r");
  24. if (fp != NULL || errno != ENOENT) {
  25. perror("(sanity check) fopen with empty filename did not fail with ENOENT");
  26. return 1;
  27. }
  28. /* sanity check: try fopening dir in write mode (must fail) */
  29. fp = fopen(PATH, "w");
  30. if (fp != NULL || errno != EISDIR) {
  31. perror("(sanity check) fopen of dir with write access did not fail");
  32. return 1;
  33. }
  34. /* creating file within Graphene (requires sgx.allow_file_creation = 1) */
  35. int fd = openat(AT_FDCWD, "tmp/filecreatedbygraphene", O_WRONLY | O_CREAT | O_TRUNC, 0666);
  36. if (fd < 0) {
  37. perror("failed to create file from within Graphene");
  38. return 1;
  39. }
  40. reti = close(fd);
  41. if (reti < 0) {
  42. perror("fclose failed");
  43. return 1;
  44. }
  45. /* write to file */
  46. fp = fopen(filepath, "w");
  47. if (fp == NULL) {
  48. perror("fopen failed");
  49. return 1;
  50. }
  51. rets = fwrite(MSG, sizeof(MSG), 1, fp); /* with NULL byte for later printf */
  52. if (rets != 1) {
  53. perror("fwrite failed");
  54. return 1;
  55. }
  56. reti = fclose(fp);
  57. if (reti) {
  58. perror("fclose failed");
  59. return 1;
  60. }
  61. /* read from same file */
  62. fp = fopen(filepath, "r");
  63. if (fp == NULL) {
  64. perror("fopen failed");
  65. return 1;
  66. }
  67. char buf[256];
  68. rets = fread(buf, 1, sizeof(buf), fp);
  69. if (rets != sizeof(MSG)) {
  70. perror("fread failed");
  71. return 1;
  72. }
  73. reti = fclose(fp);
  74. if (reti) {
  75. perror("fclose failed");
  76. return 1;
  77. }
  78. reti = printf("Successfully read from file: %s\n", buf);
  79. if (reti < 0) {
  80. perror("printf failed");
  81. return 1;
  82. }
  83. return 0;
  84. }