fopen_cornercases.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #define FILENAME_MAX_LENGTH 255
  6. #define PATH "tmp/"
  7. #define MSG "Hello World"
  8. int main(int argc, char** argv) {
  9. size_t rets;
  10. int reti;
  11. char filename[FILENAME_MAX_LENGTH];
  12. memset(filename, 'a', sizeof(filename));
  13. filename[FILENAME_MAX_LENGTH-1] = '\0';
  14. char filepath[sizeof(PATH) + sizeof(filename) - 1];
  15. strcpy(filepath, PATH);
  16. strcat(filepath, filename);
  17. printf("filepath = %s (len = %lu)\n", filepath, strlen(filepath));
  18. /* sanity check: try fopening dir in write mode (must fail) */
  19. errno = 0;
  20. FILE* fp = fopen(PATH, "w");
  21. if (fp != NULL || errno != EISDIR) {
  22. perror("(sanity check) fopen of dir with write access did not fail");
  23. return 1;
  24. }
  25. /* write to file */
  26. fp = fopen(filepath, "w");
  27. if (fp == NULL) {
  28. perror("fopen failed");
  29. return 1;
  30. }
  31. rets = fwrite(MSG, sizeof(MSG), 1, fp); /* with NULL byte for later printf */
  32. if (rets != 1) {
  33. perror("fwrite failed");
  34. return 1;
  35. }
  36. reti = fclose(fp);
  37. if (reti) {
  38. perror("fclose failed");
  39. return 1;
  40. }
  41. /* read from same file */
  42. fp = fopen(filepath, "r");
  43. if (fp == NULL) {
  44. perror("fopen failed");
  45. return 1;
  46. }
  47. char buf[256];
  48. rets = fread(buf, 1, sizeof(buf), fp);
  49. if (rets != sizeof(MSG)) {
  50. perror("fread failed");
  51. return 1;
  52. }
  53. reti = fclose(fp);
  54. if (reti) {
  55. perror("fclose failed");
  56. return 1;
  57. }
  58. reti = printf("Successfully read from file: %s\n", buf);
  59. if (reti < 0) {
  60. perror("printf failed");
  61. return 1;
  62. }
  63. return 0;
  64. }