fopen_cornercases.c 2.4 KB

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