我正在尝试使用C中的Dirent Header文件读取目录。
我无法在char数组中的给定目录中存储文件名。
代码如下。
char * FileNames;
while ( ( DirentPointer = readdir(DirectoryPointer) ) != NULL) {
strcpy(&FileNames[Counter], DirentPointer -> d_name);
Counter++;
}
当我运行应用程序时,我遇到了分段错误。我认为由于内存分配,strcpy会导致应用程序错误。
有人能告诉我如何使用malloc和realloc动态地将内存分配添加到FileNames Char *中吗?
答案 0 :(得分:1)
您的代码会产生未定义的行为,或者很可能会崩溃。这是因为FileNames
是指向字符的指针,而不是用于复制字符串的内存缓冲区,函数strcpy
不会检查要复制到的缓冲区。所以strcpy
会尝试写入你没有为此目的分配的内存。您需要先分配内存来复制文件名。
#define MAX_FILE_NUM 1000
char *FileNames[MAX_FILE_NUM] = {0}; // initialize to NULL
int Counter = 0;
while((DirentPointer = readdir(DirectoryPointer)) != NULL) {
FileNames[counter] = malloc(strlen(DirentPointer->d_name) + 1); // + 1 for the null byte
// check for NULL
if(FileNames[i] != NULL) {
strcpy(FileNames[i], DirentPointer->d_name);
Counter++;
}
else {
// handle the NULL case
// maybe try malloc again
}
}
// after you are done with the FileNames
for(int i = 0; i < Counter; i++) {
free(FileNames[i]);
FileNames[i] = NULL;
}