bug-fseek.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. static char *fname;
  6. static void do_prepare (void);
  7. #define PREPARE(argc, argv) do_prepare ()
  8. static int do_test (void);
  9. #define TEST_FUNCTION do_test ()
  10. #include <test-skeleton.c>
  11. static void
  12. do_prepare (void)
  13. {
  14. static const char pattern[] = "12345678901234567890";
  15. int fd = create_temp_file ("bug-fseek.", &fname);
  16. if (fd == -1)
  17. {
  18. printf ("cannot create temporary file: %m\n");
  19. exit (1);
  20. }
  21. if (write (fd, pattern, sizeof (pattern)) != sizeof (pattern))
  22. {
  23. perror ("short write");
  24. abort ();
  25. }
  26. close (fd);
  27. }
  28. static int
  29. do_test (void)
  30. {
  31. FILE *f;
  32. int result = 0;
  33. char buf[10];
  34. if ((f = fopen (fname, "r")) == (FILE *) NULL)
  35. {
  36. perror ("fopen(\"r\")");
  37. }
  38. fread (buf, 3, 1, f);
  39. errno = 0;
  40. if (fseek (f, -10, SEEK_CUR) == 0)
  41. {
  42. printf ("fseek() for r to before start of file worked!\n");
  43. result = 1;
  44. }
  45. else if (errno != EINVAL)
  46. {
  47. printf ("\
  48. fseek() for r to before start of file did not set errno to EINVAL. \
  49. Got %d instead\n",
  50. errno);
  51. result = 1;
  52. }
  53. fclose (f);
  54. if ((f = fopen (fname, "r+")) == (FILE *) NULL)
  55. {
  56. perror ("fopen(\"r+\")");
  57. }
  58. fread (buf, 3, 1, f);
  59. errno = 0;
  60. if (fseek (f, -10, SEEK_CUR) == 0)
  61. {
  62. printf ("fseek() for r+ to before start of file worked!\n");
  63. result = 1;
  64. }
  65. else if (errno != EINVAL)
  66. {
  67. printf ("\
  68. fseek() for r+ to before start of file did not set errno to EINVAL. \
  69. Got %d instead\n",
  70. errno);
  71. result = 1;
  72. }
  73. fclose (f);
  74. if ((f = fopen (fname, "r+")) == (FILE *) NULL)
  75. {
  76. perror ("fopen(\"r+\")");
  77. }
  78. fread (buf, 3, 1, f);
  79. if (ftell (f) != 3)
  80. {
  81. puts ("ftell failed");
  82. return 1;
  83. }
  84. errno = 0;
  85. if (fseek (f, -10, SEEK_CUR) == 0)
  86. {
  87. printf ("fseek() for r+ to before start of file worked!\n");
  88. result = 1;
  89. }
  90. else if (errno != EINVAL)
  91. {
  92. printf ("\
  93. fseek() for r+ to before start of file did not set errno to EINVAL. \
  94. Got %d instead\n",
  95. errno);
  96. result = 1;
  97. }
  98. fclose (f);
  99. return result;
  100. }