"#include <stdio.h>\n#include <string.h>\n#include <dirent.h>\n\nint main() {\n DIR *dir;\n struct dirent *entry;\n \n // 打开当前目录\n dir = opendir(".");\n if (dir == NULL) {\n printf("无法打开当前目录\n");\n return 1;\n }\n \n // 遍历目录中的所有文件\n while ((entry = readdir(dir)) != NULL) {\n // 排除当前目录和上级目录\n if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {\n continue;\n }\n \n // 打开文件\n FILE *file = fopen(entry->d_name, "r");\n if (file == NULL) {\n printf("无法打开文件: %s\n", entry->d_name);\n continue;\n }\n \n // 计算文件长度\n fseek(file, 0, SEEK_END);\n long length = ftell(file);\n fseek(file, 0, SEEK_SET);\n \n // 读取文件内容并打印\n char buffer[length];\n fread(buffer, 1, length, file);\n printf("文件名: %s\n文件内容: %s\n文件长度: %ld\n", entry->d_name, buffer, length);\n \n // 关闭文件\n fclose(file);\n }\n \n // 关闭目录\n closedir(dir);\n \n return 0;\n}\n"\n这段代码会遍历当前目录下的所有文件,打开每个文件并读取其内容,然后打印文件名、文件内容和文件长度。\n\n需要注意的是,这段代码假设所有文件的内容都能被完整地读入内存,因此对于非常大的文件可能会出现问题。如果需要处理大文件,可以使用循环读取的方式,每次读取一部分内容进行处理。

C语言读取当前目录所有文件内容并打印 - Windows 示例

原文地址: https://www.cveoy.top/t/topic/qC4X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录