LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Reading all files in a directory in an alphabetical order (https://www.linuxquestions.org/questions/programming-9/reading-all-files-in-a-directory-in-an-alphabetical-order-771200/)

weeshalll 11-24-2009 06:49 AM

Reading all files in a directory in an alphabetical order
 
Hi all,
I want to read all the files in a directory alphabetically .
How can i achieve it ?
Can i use the "readdir" function ?

catkin 11-24-2009 06:59 AM

Which programming languages are you considering?

Hko 11-24-2009 07:07 AM

You can use readdir, sure, but you would still need to code the sorting yourself.

scandir() is more convenient when you need to sort. At the end of man 3 scandir there's example code which is a ready-made program to read a directory sorted alphabetically.

bigearsbilly 11-24-2009 07:37 AM

for a quick lazy solution
you could cheat and use popen


Code:

#include <stdio.h>
#define SZ 8192
int main (int argc, char ** argv) {

    FILE *fp = popen("ls", "r");
    char buffer[SZ+1];
    while (fgets(buffer, SZ, fp)) {
        puts(buffer);
    }

    return 0;
}


weeshalll 11-24-2009 11:05 PM

Thanks for your replies

@catkin
i am using C

smeezekitty 11-25-2009 12:35 AM

Quote:

Originally Posted by bigearsbilly (Post 3767886)
for a quick lazy solution
you could cheat and use popen


Code:

#include <stdio.h>
#define SZ 8192
int main (int argc, char ** argv) {

    FILE *fp = popen("ls", "r");
    char buffer[SZ+1];
    while (fgets(buffer, SZ, fp)) {
        puts(buffer);
    }

    return 0;
}


readdir is far more portable then popen.

bigearsbilly 11-25-2009 03:19 AM

Quote:

Originally Posted by smeezekitty (Post 3768779)
readdir is far more portable then popen.

all POSIX compliant OSes have it

that's portable enough for me
:)

weeshalll 11-25-2009 10:28 PM

Thank you all for the replies ...
I checked both the solutions and they are working fine for me


All times are GMT -5. The time now is 04:32 PM.