简体   繁体   English

用C读取多个文本文件

[英]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?我知道您可以使用fopen()来获取指向文件的指针,然后执行while(fgets(..) != null){}来读取整个文件,但是我怎么能从另一个文件中读取文件? I want to loop through every file in the directory.我想遍历目录中的每个文件。

Sam, you can use opendir/readdir as in the following little function. Sam,你可以在下面的小函数中使用 opendir/readdir。

#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...但是,您可以根据需要处理文件,而不是打印名称...

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().通常,文件列表会在命令行上提供给您的程序,因此可以在作为第二个参数传递给 main() 的指针数组中使用。 ie 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.即调用 shell 用于查找目录中的所有文件,然后您的程序只是遍历 argv[] 以打开和处理(和关闭)每个文件。

See p.见第。 162 in "The C Programming Language", Kernighan and Ritchie, 2nd edition, for an almost complete template for the code you could use. 162 in "The C Programming Language", Kernighan and Ritchie, 2nd edition,为您可以使用的代码提供几乎完整的模板。 Substitute your own processing for the filecopy() function in that example.在该示例filecopy()您自己的处理替换filecopy()函数。

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.如果你真的需要直接从你的程序中读取一个目录(或多个目录),那么你需要阅读 libc 中的 opendir(3) 和相关函数。 Some systems also offer a library function called ftw(3) or fts(3) that can be quite handy too.一些系统还提供了一个名为 ftw(3) 或 fts(3) 的库函数,它们也非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM