0

I am working with Linux system.

 DIR *dir;
  struct dirent *ent;
  while ((ent = readdir (dir)) != NULL) {           
    printf ("%s\n", ent->d_name);
  }

I get "." , ".." and some file names as a result. How can I get rid of "." and ".."? I need those file names for further process. What's the type of ent->d_name?? Is it a string or char?

lulyon
  • 6,707
  • 7
  • 32
  • 49
Sycx
  • 303
  • 1
  • 3
  • 6
  • 1
    http://stackoverflow.com/questions/12991334/members-of-dirent-structure . If `d_name` were a char, then using `%s` to print it would be undefined behaviour (not to mention using one char to store an entire filename would require some amazing data compression algorithms). – DCoder Aug 25 '13 at 12:07
  • "What's the type of `ent->d_name`?? Is it a string or char?" - have you read the documentation? –  Aug 25 '13 at 12:14
  • 1
    possible duplicate of [List files without "." and ".."](http://stackoverflow.com/questions/10138624/list-files-without-and) – P0W Aug 25 '13 at 12:38

2 Answers2

2

Read the man page of readdir, get this:

struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all file system types */
               char           d_name[256]; /* filename */
           };

So ent->d_name is a char array. You could use it as a string, of course.

To get rid of "." and "..":

while ((ent = readdir (dir)) != NULL) {  
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 )
    printf ("%s\n", ent->d_name);
  }

Update

The resulting ent contains file names and file folder names. If folder names are not needed, it is better to check ent->d_type field with if(ent->d_type == DT_DIR).

lulyon
  • 6,707
  • 7
  • 32
  • 49
1

Use strcmp :

while ((ent = readdir (dir)) != NULL) {  
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)         
    //printf ("%s\n", ent->d_name);
  }
P0W
  • 46,614
  • 9
  • 72
  • 119