Originally Posted By: mlord
I can give you a basic readdir program that you can hack away at, if you like.

This could be done more robustly, using execve() rather than system(), but it's probably good enough:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>

static void do_something (const char *dpath, const char *this_name)
{
        char tmp[16384];  /* BIG dumb buffer, rather than trying to be clever */
        /*
         * Insert code here to do whatever with "this_name".
         * Here is an example of how to do something:
         */
        char destination[] = "/tmp";
        sprintf(tmp, "/bin/cp \"%s/%s\" \"%s\"", dpath, this_name, destination);
        printf("===> %s\n", tmp);
        fflush(stdout);
        if (-1 == system(tmp))
                perror(tmp);
}

int main (int argc, char *argv[])
{
        const char *dpath;
        struct dirent *de;
        DIR *dp;

        if (argc != 2) {
                fprintf(stderr, "Usage: %s <dir>\n", argv[0]);
                return 1;
        }
        dpath = argv[1];
        dp = opendir(dpath);
        if (dp == NULL) {
                perror(dpath);
                return 1;
        }
        errno = 0;
        while ((de = readdir(dp)) != NULL) {
                const char *this_name = de->d_name;
                if (strcmp(this_name, ".") && strcmp(this_name, "..")) {
                        printf("%s\n", this_name);
                        fflush(stdout);
                        do_something(dpath, this_name);
                }
                errno = 0;  /* for next readdir() call */
        }
        if (errno) {
                perror(dpath);
                return 1;
        }
        return 0;  /* all done */
}


Edited by mlord (18/01/2011 20:22)