Reading multiple text files in C

一世执手 提交于 2021-01-27 21:30:21

问题


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.


回答1:


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...




回答2:


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.



来源:https://stackoverflow.com/questions/13427070/reading-multiple-text-files-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!