我需要遍历一个目录,data
并在一个字符串中读取满足特定条件的每个文件并对其进行处理。由于某种原因,它在调用后失败fseek
(输出只是目录中第一个文件的名称)。
知道我在做什么错吗?
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
void doAlgorithm(char *input) {
printf("%s\n", input);
}
int main(int argc, char** argv) {
struct dirent *dir;
DIR *d = opendir("data");
FILE *file;
while ((dir = readdir(d)) != NULL) {
if (strlen(dir->d_name) > 6 && dir->d_name[6] == 'i') {
printf("Filename: %s\n", dir->d_name);
file = fopen(dir->d_name, "r");
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
printf(", Filesize: %ld\n", length);
char *buffer = malloc(length + 1);
fread(buffer, 1, length, file);
buffer[length] = '\0';
fclose(file);
doAlgorithm(buffer);
}
}
closedir(d);
return (EXIT_SUCCESS);
}