它是我之前问题的扩展:如何从 c 中的目录中仅获取 txt 文件?. 现在我想将这些文件名(我真的不知道目录中有多少)保存到char **
数组中。我想出了一个解决方案(有点),但后来我意识到我不需要char*
但是char **
(我知道,愚蠢的我 :])
无论如何,我用这段代码得到了分段错误[核心转储]:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdbool.h>
char* allocMemory(int n)
{
char *tab = (char *) malloc(n*sizeof(char));
return tab;
}
void freeMemory(char **tab, int n, int m)
{
int i=0;
for(i=0; i<m; i++)
free(tab[i]);
free(tab);
tab = NULL;
}
bool hasTxtExtension(char const *filename)
{
size_t len = strlen(filename);
return len > 4 && strcmp(filename + len - 4, ".txt") == 0;
}
char** getTxtFilenames(const char *dirname)
{
DIR *directory = NULL;
struct dirent *ent = NULL;
int fileCounter = 0;
char **txtFiles = allocMemory(1);
char **moreTxtFiles = allocMemory(1);
directory = opendir (dirname);
if(directory == NULL)
return NULL;
int i = 0;
while ((ent = readdir (directory)) != NULL)
{
if(hasTxtExtension(ent->d_name))
{
fileCounter ++;
moreTxtFiles = (char**) realloc (txtFiles, fileCounter * sizeof(char*));
if(moreTxtFiles[i] != NULL)
{
txtFiles = moreTxtFiles;
txtFiles[i] = allocMemory(strlen(ent->d_name));
txtFiles[i][fileCounter - 1] = ent->d_name;
}
else
{
freeMemory(txtFiles, 1, fileCounter);
return NULL;
}
}
i ++;
}
if(closedir(directory) < 0)
return NULL;
return txtFiles;
}
int main(int argc, char **argv)
{
char **txtFilenames = getTxtFilenames("dir");
if(txtFilenames == NULL)
return -1;
printf("%s\n", txtFilenames[0][1]);
return 0;
}
编辑:
我也试过这个:(请注意,我对 C 中那些不可爱的 char 数组有点困惑,啊 :/)
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdbool.h>
char* allocMemory(int n)
{
char *tab = (char *) malloc(n*sizeof(char));
return tab;
}
void freeMemory(char *tab)
{
free(tab);
tab = NULL;
}
bool hasTxtExtension(char const *filename)
{
size_t len = strlen(filename);
return len > 4 && strcmp(filename + len - 4, ".txt") == 0;
}
char* getTxtFilenames(const char *dirname)
{
DIR *directory = NULL;
struct dirent *ent = NULL;
int fileCounter = 0;
char *txtFiles = NULL;
char *moreTxtFiles = NULL;
directory = opendir (dirname);
if(directory == NULL)
return NULL;
while ((ent = readdir (directory)) != NULL)
{
if(hasTxtExtension(ent->d_name))
{
fileCounter ++;
moreTxtFiles = (char*) realloc (txtFiles, fileCounter * sizeof(char));
if(moreTxtFiles != NULL)
{
txtFiles = moreTxtFiles;
txtFiles[fileCounter - 1] = ent->d_name;
}
else
{
freeMemory(txtFiles);
return NULL;
}
}
}
if(closedir(directory) < 0)
return NULL;
return txtFiles;
}
int main(int argc, char **argv)
{
char **txtFilenames = getTxtFilenames("dir");
if(txtFilenames == NULL)
return -1;
printf("%s\n", txtFilenames[0]);
return 0;
}