Mingw x86_64 v11.2.0
Windows 10 21H2我当前的问题是,这个函数通常可以读取目录中的文件和文件夹,但是如果它保存在指针中并打印在屏幕上,那么单个文件将反复出现。
这些是目录中的文件。
.
..
main.c
main.exe
README.md
test.txt以下是我编写的源代码:
#include "../DeleteCompletely.h"
#include <dirent.h>
#define TotalNumber 4096
#define TotalFileNameLen 4096
typedef struct dirent DIRENT;
typedef struct {
DIR *dir_ptr;
DIRENT *dirent_ptr;
char **pathSet;
size_t number;
} snDIR;
static snDIR *getAllFile(const char *path)
{
snDIR *dirSet = (snDIR *)malloc(sizeof(snDIR));
dirSet->dir_ptr = opendir(path);
size_t loopIndex;
dirSet->pathSet = (char **)malloc(sizeof(char **) * TotalNumber);
if(dirSet->dir_ptr) {
dirSet->number = 0;
loopIndex = 0;
while ((dirSet->dirent_ptr = readdir(dirSet->dir_ptr)) != NULL) {
dirSet->pathSet[loopIndex] = (char *)malloc(TotalFileNameLen);
dirSet->pathSet[loopIndex] = dirSet->dirent_ptr->d_name;
dirSet->number++;
loopIndex++;
}
closedir(dirSet->dir_ptr);
}
return dirSet;
}
int main(int argc, char **argv)
{
snDIR *set = getAllFile(".");
for(size_t x = 0; x < set->number; ++x) {
printf("%s\n", set->pathSet[x]);
}
free(set);
return 0;
}发布于 2022-09-27 05:36:36
问题是这些作业:
dirSet->pathSet[loopIndex] = (char *)malloc(TotalFileNameLen);
dirSet->pathSet[loopIndex] = dirSet->dirent_ptr->d_name;第一个make dirSet->pathSet[loopIndex]指向一个位置。第二种方法使之指向完全不同的地方。
而不是第二个赋值,您需要复制字符串。
strcpy(dirSet->pathSet[loopIndex], dirSet->dirent_ptr->d_name);你也浪费了相当多的内存,因为你总是分配大量的内存。字符串如此大的可能性是相当小的。相反,使用字符串长度作为基本大小:
dirSet->pathSet[loopIndex] = malloc(strlen(dirSet->dirent_ptr->d_name) + 1);
// +1 for the null terminatorhttps://stackoverflow.com/questions/73862758
复制相似问题