tst-seekdir.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. off_t save0, rewind_ret;
  16. dirp = opendir (".");
  17. if (dirp == NULL)
  18. {
  19. printf ("opendir failed: %s\n", strerror(errno));
  20. return 1;
  21. }
  22. save0 = telldir (dirp);
  23. if (save0 == -1)
  24. {
  25. printf ("telldir failed: %s\n", strerror(errno));
  26. result = 1;
  27. }
  28. for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
  29. {
  30. /* save position 3 (after fourth entry) */
  31. if (i++ == 3)
  32. save3 = telldir (dirp);
  33. printf ("%s\n", dp->d_name);
  34. /* stop at 400 (just to make sure dirp->__offset and dirp->__size are
  35. scrambled */
  36. if (i == 400)
  37. break;
  38. }
  39. printf ("going back past 4-th entry...\n");
  40. /* go back to saved entry */
  41. seekdir (dirp, save3);
  42. /* Check whether telldir equals to save3 now. */
  43. cur = telldir (dirp);
  44. if (cur != save3)
  45. {
  46. printf ("seekdir (d, %ld); telldir (d) == %ld\n", save3, cur);
  47. result = 1;
  48. }
  49. /* print remaining files (3-last) */
  50. for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
  51. printf ("%s\n", dp->d_name);
  52. /* Check rewinddir */
  53. rewinddir (dirp);
  54. rewind_ret = telldir (dirp);
  55. if (rewind_ret == -1)
  56. {
  57. printf ("telldir failed: %s\n", strerror(errno));
  58. result = 1;
  59. }
  60. else if (save0 != rewind_ret)
  61. {
  62. printf ("rewinddir didn't reset directory stream\n");
  63. result = 1;
  64. }
  65. closedir (dirp);
  66. return result;
  67. }