それは私の前の質問の拡張です:どうすればcのディレクトリからtxtファイルだけを取得できますか?。次に、これらのファイル名(dirにいくつあるかはわかりません)を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;
}
編集:
私もこれを試しました:(ImがCの素敵ではないchar配列と少し混同されていることに注意してください、argh:/)
#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;
}