我正在尝试使用getDirectoryFiles函数将目录中的所有文件名获取到文件数组中,但是不幸的是,当我尝试在循环中打印文件名时出现此错误。任何帮助将不胜感激。
p.s:我知道那里有几个函数可以执行相同的操作,但是我需要像我的项目那样构建它。
错误:抛出未处理的异常:读取访问冲突。 filesArray 为0x1110112。发生
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#define FILE_NAME_MAX_SIZE 50
#define ERROR_WITH_OPENING_THE_FILE -1
#define MAX_AMOUNT_OF_BYTES_TO_READ 1000
#define FALSE 0
#define TRUE 1
// Declaring functions
int getDirectoryFiles(char* dirPath, char** filesArray);
int main(int argc, char* argv[])
{
// Declaring varibles
char** filesArray = 0;
int filesAmount = 0;
// Getting all the files from the directory with the getDirectoryFiles function
filesAmount = getDirectoryFiles(argv[1], filesArray);
printf("%s\n", filesArray[0]); // Getting the error here
getchar();
return 0;
}
int getDirectoryFiles(char* dirPath, char** filesArray)
{
// Declaring varibles
DIR *d;
struct dirent *dir;
int filesCounter = 0;
int i = 0;
// Opening the directory and checking if it's openable
d = opendir(dirPath);
if (!d)
{
filesCounter = ERROR_WITH_OPENING_THE_FILE;
}
if (!filesCounter)
{
// Counting the amount of files in the directory
while ((dir = readdir(d)) != NULL)
{
if (strcmp(".", dir->d_name) && strcmp("..", dir->d_name) && dir->d_type != DT_DIR)
{
filesCounter++;
}
}
// Closing the directory and opening it again in order to read from the first file
closedir(d);
d = opendir(dirPath);
// Inserting the files names into the files array
filesArray = (char**)malloc(sizeof(char*) * filesCounter);
while ((dir = readdir(d)) != NULL)
{
if (strcmp(".", dir->d_name) && strcmp("..", dir->d_name) && dir->d_type != DT_DIR)
{
*(filesArray + i) = (char*)calloc(FILE_NAME_MAX_SIZE, sizeof(char));
strcpy(filesArray[i], dir->d_name);
i++;
}
}
}
// Closing the directory
closedir(d);
return filesCounter;
}