How to sort files in some directory by the names on Linux

前端 未结 3 757
轻奢々
轻奢々 2020-12-17 16:25

I use opendir() and readdir() to display the file names in a directory. But they are disordered. How can I sort them? The language is C.

3条回答
  •  悲&欢浪女
    2020-12-17 17:09

    Maybe you could use scandir() instead of opendir and readdir?

    #include 
    #include 
    #include 
    
    int
    main(void)
    {
       struct dirent **namelist;
       int n;
    
       n = scandir(".", &namelist, 0, alphasort);
       if (n < 0)
           perror("scandir");
       else {
           while (n--) {
           printf("%s\n", namelist[n]->d_name);
           free(namelist[n]);
           }
           free(namelist);
       }
    }
    

提交回复
热议问题