当我尝试将所有文件小于特定大小时,会出现此问题。在下面的代码中,如果size_smaller
为-1,那么代码将以递归方式打印目录中的所有文件(这是有效的)。如果我将size_smaller
设置为我想要打印小于size_smaller
的文件的值,则不会。它将在根目录中打印较小值的文件,但不在子目录中打印。希望你明白。
这是代码:
void list_recursive(char* path, int size_smaller){
DIR* dir;
struct dirent *dirent;
char * name = malloc(sizeof(char) * MAX_LEN);
dir = opendir(path);
if(dir != NULL){
if(isRec == 0){
printf("SUCCESS\n");
}
while((dirent = readdir(dir)) != NULL){
if(strcmp(dirent->d_name, ".") != 0 && strcmp(dirent->d_name, "..") != 0){
if(size_smaller == -1){
sprintf(name, "%s/%s", path, dirent->d_name);
printf("%s\n", name);
}
else if(size_smaller != -1 && dirent->d_type == DT_REG){
size_t sizeToCheck;
sprintf(name, "%s/%s", path, dirent->d_name);
FILE *fp;
fp = fopen(name, "r");
fseek(fp, 0, SEEK_END);
sizeToCheck = ftell(fp);
printf("\n%zu\n\n", sizeToCheck);
if(sizeToCheck < size_smaller){
printf("%s\n\n", name);
}
fclose(fp);
}
if(dirent->d_type == DT_DIR){
isRec = 1;
list_recursive(name, size_smaller);
}
}
}
free(name);
closedir(dir);
}
else {
printf("ERROR\n");
printf("invalid directory path\n");
}
}
答案 0 :(得分:0)
我找到了解决方案。
问题出在此处:if(size_smaller == -1){
sprintf(name, "%s/%s", path, dirent->d_name);
printf("%s\n", name);
}
只需将sprintf(name, "%s/%s", path, dirent->d_name);
放在if。