displaying files from directory

橙三吉。 提交于 2019-12-12 02:19:45

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17707050/displaying-files-from-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!