سؤال

I have a directory name called dir. It contain following files in order

12.07.2013
13.07.2013
14.07.2013
15.07.2013
16.07.2013
17.07.2013

I wrote following C program to display all the files from the directory dir

code :

#include <stdio.h>
#include <string.h>
#include <dirent.h>
int main (int argc, char *argv[])
{
    DIR *directory;
    struct dirent *file;     
    directory = opendir (argv[1]);
    if (directory != NULL){
        while (file = readdir (directory))
              printf("FILE : %s \n",file->d_name);

        (void) closedir (directory);
        }
   else
        printf("Not able to open the directory\n");
   return 0;
}

Above code give the actual output as

FILE : 14.07.2013 
FILE : 13.07.2013 
FILE : 17.07.2013 
FILE : . 
FILE : 15.07.2013 
FILE : .. 
FILE : 12.07.2013 
FILE : 16.07.2013 

but i expected output in proper order like below

FILE : 12.07.2013 
FILE : 13.07.2013 
FILE : 14.07.2013 
FILE : 15.07.2013 
FILE : 16.07.2013 
FILE : 17.07.2013 

When i directly see the files in directory it arranges & diplaying the files in proper order.

Then why above C code not reading file in proper order, i mean randomly reading the file.

Working environment : Linux(ubuntu12.04), gcc compiler

Thanks

هل كانت مفيدة؟

المحلول

It's not randomly reading the files, it's just reading the directory listing in the order it's stored in the directory file itself. When you "directly see the files in directory", I presume that means you're using ls, but ls is sorting the results before output. If you want matching output you need to do the same.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top