开发者

How to retrieve file names and subdirectory names from a directory in C?

Ok I have something like this:

struct dirent *dp;
DIR *dir;
char fullname[MAXPATHLEN];
char** tmp_paths = argv[1]; //Not the exact code but you get the idea.

...

while ((dp = readdir(dir)) != NULL)
{
    struct stat stat_buffer;

    sprintf(fullname, "%s/%s", *tmp_paths, dp->d_name);

    if (stat(fullname, &stat_buffer) != 0)
        perror(opts.programname);

    /* Processing 开发者_如何学Pythonfiles */
    if (S_ISDIR(stat_buffer.st_mode))
    {
        nSubdirs++;
        DIRECTORYINFO* subd = malloc(BUFSIZ);
    }

    /* Processing subdirs */
    if (S_ISREG(stat_buffer.st_mode))
    {
        nFiles++;
        FILEINFO *f = malloc(BUFSIZ);
    }
}

How do I go about reading in the file names and subdirectory names into my own structure DIRECTORYINFO and FILEINFO? I've gone through stat.h and haven't found anything useful.


In the UNIX world the name is not part of the file, so stat(2) cannot retrieve information about it. But in your code you have the name as dp->d_name, so you can copy that string into your own data structure. That should be fairly simple.

If this is not your problem I didn't understand the question.


Take a look at this question and its answers. You probably want to use dirent->d_name.


Glob is your friend

The glob() function searches for all the pathnames matching pattern according to the rules used by the shell

/* Sample Code */
#include <glob.h>    
glob_t data;
glob("*", 0, NULL, &data ); /* Here "*" says to match all files of the current dir */
for(int i=0; i<data.gl_pathc; i++)
{
    /* Printing all the path names,Just for illustration */
    printf( "%s\n", data.gl_pathv[i] );
}
/* To split into DIRINFO and FILEINFO, stat(2) should be made use of */
globfree( &data ); /* free the data structure */

To get more details you can always use the unix man page

man glob

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜