在C中读取多个文本文件 [英] Reading multiple text files in C
问题描述
当您知道目录中会有很多文件时,从文本文件读取和提取数据的正确方法是什么?我知道您可以使用 fopen()
来获取指向文件的指针,然后执行 while(fgets(..)!= null){}
这样的操作来从整个文件中读取,但是如何从另一个文件中读取?我想遍历目录中的每个文件.
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.
推荐答案
Sam,您可以像下面的小功能一样使用opendir/readdir.
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...
这篇关于在C中读取多个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!