开发者

Getting list of files in a folder using C

开发者 https://www.devze.com 2023-01-21 23:15 出处:网络
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?

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 开发者_如何学PythonC99?

How can I get a list of its folders?

Any help is appreciated.


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.


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;
}


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号