tst-seekdir.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <errno.h>
  4. #include <dirent.h>
  5. #include <stdlib.h>
  6. int
  7. main (int argc, char *argv[])
  8. {
  9. DIR * dirp;
  10. long int save3 = 0;
  11. long int cur;
  12. int i = 0;
  13. int result = 0;
  14. struct dirent *dp;
  15. long int save0;
  16. long int rewind;
  17. dirp = opendir (".");
  18. if (dirp == NULL)
  19. {
  20. printf ("opendir failed: %s\n", strerror(errno));
  21. return 1;
  22. }
  23. save0 = telldir (dirp);
  24. if (save0 == -1)
  25. {
  26. printf ("telldir failed: %s\n", strerror(errno));
  27. result = 1;
  28. }
  29. for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
  30. {
  31. /* save position 3 (after fourth entry) */
  32. if (i++ == 3)
  33. save3 = telldir (dirp);
  34. printf ("%s\n", dp->d_name);
  35. /* stop at 400 (just to make sure dirp->__offset and dirp->__size are
  36. scrambled */
  37. if (i == 400)
  38. break;
  39. }
  40. printf ("going back past 4-th entry...\n");
  41. /* go back to saved entry */
  42. seekdir (dirp, save3);
  43. /* Check whether telldir equals to save3 now. */
  44. cur = telldir (dirp);
  45. if (cur != save3)
  46. {
  47. printf ("seekdir (d, %ld); telldir (d) == %ld\n", save3, cur);
  48. result = 1;
  49. }
  50. /* print remaining files (3-last) */
  51. for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
  52. printf ("%s\n", dp->d_name);
  53. /* Check rewinddir */
  54. rewinddir (dirp);
  55. rewind = telldir (dirp);
  56. if (rewind == -1)
  57. {
  58. printf ("telldir failed: %s\n", strerror(errno));
  59. result = 1;
  60. }
  61. else if (save0 != rewind)
  62. {
  63. printf ("rewinddir didn't reset directory stream\n");
  64. result = 1;
  65. }
  66. closedir (dirp);
  67. return result;
  68. }