c语言批量读取txt文件
时间: 2023-09-09 16:13:15 浏览: 175
以下是一个示例代码,可以批量读取指定文件夹下的所有txt文件:
```c
#include <stdio.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
char path[256] = "/path/to/folder/"; // 指定文件夹路径
char filename[256];
if ((dir = opendir(path)) != NULL) {
// 读取文件夹中的文件
while ((ent = readdir(dir)) != NULL) {
// 排除非txt文件
if (strstr(ent->d_name, ".txt") == NULL) {
continue;
}
// 构建文件完整路径
strcpy(filename, path);
strcat(filename, ent->d_name);
// 读取txt文件内容
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("无法打开文件:%s\n", filename);
} else {
printf("文件内容:%s\n", filename);
char buffer[1024];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
}
}
closedir(dir);
} else {
printf("无法打开文件夹:%s\n", path);
}
return 0;
}
```
需要注意的是,这个代码只是一个示例,实际应用中可能需要根据具体情况进行一些修改和优化。例如,可以将文件路径和文件名的拼接过程封装为一个函数,更加方便使用。