Sycx
Sycx

Reputation: 351

how can i get all file name in a directory without getting "." and ".." in C

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?

Upvotes: -1

Views: 6749

Answers (2)

lulyon
lulyon

Reputation: 7265

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).

Upvotes: 2

P0W
P0W

Reputation: 47824

Use strcmp :

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

Upvotes: 1

Related Questions