user182513
user182513

Reputation:

Getting list of files in a folder using C

I have path to a folder for example

/myfolder

or in Windows:

C:\myfolder

and I want to get a list of all files in that folder. How shall I do so in C?

Is it different in C++ or C99?

How can I get a list of its folders?

Any help is appreciated.

Upvotes: 5

Views: 5824

Answers (5)

herohuyongtao
herohuyongtao

Reputation: 50657

Check out the get_all_files_within_folder() I wrote in C/C++ here, which I answered a similar question as yours. It works perfectly for me. Hope it helps.

Upvotes: 1

Gary Willoughby
Gary Willoughby

Reputation: 52498

You can use the functions declared in dirent.h

dirent.h is the header in the C POSIX library for the C programming language that contains constructs that facilitate directory traversing. The function is not part of the C standard, but is considered "pseudo-standard" and is usually portable between platforms.
http://en.wikipedia.org/wiki/Dirent.h

#include <dirent.h>

int main(int argc, char **argv)
{
    DIR *dir;
    struct dirent *de;

    dir = opendir("."); /*your directory*/
    while(dir)
    {
        de = readdir(dir);
        if (!de) break;
        printf("%i %s\n", de->d_type, de->d_name);
    }
    closedir(dir);
    return 0;
}

Upvotes: 4

StNickolay
StNickolay

Reputation: 960

This is classical task, one possiple solution maybe find in Kernigan & Ritchie - The C programming Language (Chapter 8.6). Essence of task is recursive traverse of target folder and its subfolders.

Upvotes: 0

Jeremy Friesner
Jeremy Friesner

Reputation: 73041

In POSIX operating systems, you can call opendir() and readdir(). In Windows you can call _findfirst() and _findnext(). With a little effort you can implement your own opendir() and readdir() as wrapper functions under Windows, so that your application code can use the same API everywhere. An example of that can be found here.

Upvotes: 4

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36423

The best approach in C++ is using boost filesystem.

As for C, you will need platform API (POSIX/WinAPI).

POSIX documentation + example: http://www.opengroup.org/onlinepubs/009695399/functions/readdir.html

Upvotes: 2

Related Questions