How can I get the list of files in a directory using C or C++?

前端 未结 27 3247
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  感情败类
    2020-11-21 06:07

    For a C only solution, please check this out. It only requires an extra header:

    https://github.com/cxong/tinydir

    tinydir_dir dir;
    tinydir_open(&dir, "/path/to/dir");
    
    while (dir.has_next)
    {
        tinydir_file file;
        tinydir_readfile(&dir, &file);
    
        printf("%s", file.name);
        if (file.is_dir)
        {
            printf("/");
        }
        printf("\n");
    
        tinydir_next(&dir);
    }
    
    tinydir_close(&dir);
    

    Some advantages over other options:

    • It's portable - wraps POSIX dirent and Windows FindFirstFile
    • It uses readdir_r where available, which means it's (usually) threadsafe
    • Supports Windows UTF-16 via the same UNICODE macros
    • It is C90 so even very ancient compilers can use it

提交回复
热议问题