Back to index

glibc  2.9
tst-seekdir.c
Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <dirent.h>
00003 #include <stdlib.h>
00004 
00005 int
00006 main (int argc, char *argv[])
00007 {
00008   DIR * dirp;
00009   long int save3 = 0;
00010   long int cur;
00011   int i = 0;
00012   int result = 0;
00013   struct dirent *dp;
00014   long int save0;
00015   long int rewind;
00016 
00017   dirp = opendir (".");
00018   if (dirp == NULL)
00019     {
00020       printf ("opendir failed: %m\n");
00021       return 1;
00022     }
00023 
00024   save0 = telldir (dirp);
00025   if (save0 == -1)
00026     {
00027       printf ("telldir failed: %m\n");
00028       result = 1;
00029     }
00030 
00031   for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
00032     {
00033       /* save position 3 (after fourth entry) */
00034       if (i++ == 3)
00035        save3 = telldir (dirp);
00036 
00037       printf ("%s\n", dp->d_name);
00038 
00039       /* stop at 400 (just to make sure dirp->__offset and dirp->__size are
00040         scrambled */
00041       if (i == 400)
00042        break;
00043     }
00044 
00045   printf ("going back past 4-th entry...\n");
00046 
00047   /* go back to saved entry */
00048   seekdir (dirp, save3);
00049 
00050   /* Check whether telldir equals to save3 now.  */
00051   cur = telldir (dirp);
00052   if (cur != save3)
00053     {
00054       printf ("seekdir (d, %ld); telldir (d) == %ld\n", save3, cur);
00055       result = 1;
00056     }
00057 
00058   /* print remaining files (3-last) */
00059   for (dp = readdir (dirp); dp != NULL; dp = readdir (dirp))
00060     printf ("%s\n", dp->d_name);
00061 
00062   /* Check rewinddir */
00063   rewinddir (dirp);
00064   rewind = telldir (dirp);
00065   if (rewind == -1)
00066     {
00067       printf ("telldir failed: %m\n");
00068       result = 1;
00069     }
00070   else if (save0 != rewind)
00071     {
00072       printf ("rewinddir didn't reset directory stream\n");
00073       result = 1;
00074     }
00075 
00076   closedir (dirp);
00077   return result;
00078 }