Windows下用C语言读取本目录下所有文件内容打印并记录文件长度
以下是一个使用C语言在Windows下读取本目录下所有文件内容并打印的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
void printFileContents(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open file: %s\n", filename);
return;
}
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
char* buffer = (char*)malloc(length + 1);
if (buffer == NULL) {
printf("Failed to allocate memory for file: %s\n", filename);
fclose(file);
return;
}
fread(buffer, 1, length, file);
buffer[length] = '\0'; // Null-terminate the string
printf("File: %s\n", filename);
printf("Length: %ld\n", length);
printf("Content:\n%s\n", buffer);
free(buffer);
fclose(file);
}
int main() {
DIR* directory = opendir(".");
if (directory == NULL) {
printf("Failed to open directory.\n");
return 1;
}
struct dirent* entry;
while ((entry = readdir(directory)) != NULL) {
if (entry->d_type == DT_REG) {
printFileContents(entry->d_name);
printf("\n");
}
}
closedir(directory);
return 0;
}
该程序首先使用opendir打开当前目录,然后使用readdir遍历目录中的所有文件。对于每个文件,使用printFileContents函数进行读取和打印操作。
printFileContents函数首先使用fopen打开文件,然后使用fseek和ftell获取文件长度。接着使用malloc动态分配内存用于存储文件内容,使用fread读取文件内容,并在末尾添加空字符以便于打印。最后打印文件名、长度和内容,并释放内存和关闭文件。
注意,该程序假设所有文件都是文本文件,如果有非文本文件可能会出现乱码或者其他问题。如果需要处理非文本文件,可以使用二进制模式打开文件,并逐字节读取内容
原文地址: https://www.cveoy.top/t/topic/iW5T 著作权归作者所有。请勿转载和采集!