tst-mmap-eofsync.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* Test program for synchronization of stdio state with file after EOF. */
  2. #include <stdio.h>
  3. #include <error.h>
  4. #include <errno.h>
  5. static void do_prepare (void);
  6. #define PREPARE(argc, argv) do_prepare ()
  7. static int do_test (void);
  8. #define TEST_FUNCTION do_test ()
  9. #include <test-skeleton.c>
  10. static char *temp_file;
  11. static int temp_fd;
  12. static char text1[] = "Line the first\n";
  13. static char text2[] = "Line the second\n";
  14. static void
  15. do_prepare (void)
  16. {
  17. temp_fd = create_temp_file ("tst-mmap-eofsync.", &temp_file);
  18. if (temp_fd == -1)
  19. error (1, errno, "cannot create temporary file");
  20. else
  21. {
  22. ssize_t cc = write (temp_fd, text1, sizeof text1 - 1);
  23. if (cc != sizeof text1 - 1)
  24. error (1, errno, "cannot write to temporary file");
  25. }
  26. }
  27. static int
  28. do_test (void)
  29. {
  30. FILE *f;
  31. char buf[128];
  32. int result = 0;
  33. int c;
  34. f = fopen (temp_file, "rm");
  35. if (f == NULL)
  36. {
  37. perror (temp_file);
  38. return 1;
  39. }
  40. if (fgets (buf, sizeof buf, f) == NULL)
  41. {
  42. perror ("fgets");
  43. return 1;
  44. }
  45. if (strcmp (buf, text1))
  46. {
  47. printf ("read \"%s\", expected \"%s\"\n", buf, text1);
  48. result = 1;
  49. }
  50. printf ("feof = %d, ferror = %d immediately after fgets\n",
  51. feof (f), ferror (f));
  52. #if 1
  53. c = fgetc (f);
  54. if (c == EOF)
  55. printf ("fgetc -> EOF (feof = %d, ferror = %d)\n",
  56. feof (f), ferror (f));
  57. else
  58. {
  59. printf ("fgetc returned %o (feof = %d, ferror = %d)\n",
  60. c, feof (f), ferror (f));
  61. result = 1;
  62. }
  63. #endif
  64. c = write (temp_fd, text2, sizeof text2 - 1);
  65. if (c == sizeof text2 - 1)
  66. printf ("wrote more to file\n");
  67. else
  68. {
  69. printf ("wrote %d != %zd (%m)\n", c, sizeof text2 - 1);
  70. result = 1;
  71. }
  72. if (fgets (buf, sizeof buf, f) == NULL)
  73. {
  74. printf ("second fgets fails: feof = %d, ferror = %d (%m)\n",
  75. feof (f), ferror (f));
  76. clearerr (f);
  77. if (fgets (buf, sizeof buf, f) == NULL)
  78. {
  79. printf ("retry fgets fails: feof = %d, ferror = %d (%m)\n",
  80. feof (f), ferror (f));
  81. result = 1;
  82. }
  83. }
  84. if (result == 0 && strcmp (buf, text2))
  85. {
  86. printf ("second time read \"%s\", expected \"%s\"\n", buf, text2);
  87. result = 1;
  88. }
  89. fclose (f);
  90. return result;
  91. }