Sam
Sam

Reputation: 2347

Reading multiple text files in C

What is the correct way to read and extract data from text files when you know that there will be many in a directory? I know that you can use fopen() to get the pointer to the file, and then do something like while(fgets(..) != null){} to read from the entire file, but then how could I read from another file? I want to loop through every file in the directory.

Upvotes: 2

Views: 6996

Answers (2)

William Morris
William Morris

Reputation: 3684

Sam, you can use opendir/readdir as in the following little function.

#include <stdio.h>
#include <dirent.h>

static void scan_dir(const char *dir)
{
    struct dirent * entry;
    DIR *d = opendir( dir );

    if (d == 0) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(d)) != 0) {
        printf("%s\n", entry->d_name);
        //read your file here
    }
    closedir(d);
}


int main(int argc, char ** argv)
{
    scan_dir(argv[1]);
    return 0;
}

This just opens a directory named on the command line and prints the names of all files it contains. But instead of printing the names, you can process the files as you like...

Upvotes: 2

Greg A. Woods
Greg A. Woods

Reputation: 2792

Typically a list of files is provided to your program on the command line, and thus are available in the array of pointers passed as the second parameter to main(). i.e. the invoking shell is used to find all the files in the directory, and then your program just iterates through argv[] to open and process (and close) each one.

See p. 162 in "The C Programming Language", Kernighan and Ritchie, 2nd edition, for an almost complete template for the code you could use. Substitute your own processing for the filecopy() function in that example.

If you really need to read a directory (or directories) directly from your program, then you'll want to read up on the opendir(3) and related functions in libc. Some systems also offer a library function called ftw(3) or fts(3) that can be quite handy too.

Upvotes: 1

Related Questions