|
ディレクトリ内のファイル情報を構造体に格納するプログラムを作成しています。
50個ほどは適切にファイルを構造体に読み込んでいるのですが、途中で
Secmentation fault (core dumped)
というエラーが出ています。
ファイル名を格納する配列を50などと減らすと、多くのファイルを読み込むようにはなります。
しかし、このPCのメモリは256mなため、余裕で確保できると思ったのですが、確保の仕方がまずいのでしょうか。
reallocの行が怪しいと思ったのですが、解決することができませんでした。
もし間違っている記述などありましたら、教えていただけると幸いです。
以下はエラーの出た部分の最小限のプログラムです。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
struct filein{
char filename[129];
int filesize;
char filetime[25];
char fileuname[9];
};
main(int argc, char *argv[])
{
DIR *dir;
struct filein *file_st;
struct dirent *dp;
int i=0;/*ルートとかの.を省く*/
char path[512],chk;
if(argc<=1) {
strcpy(path,".");
}
else{
strcpy(path,argv[1]);
}
if((dir=opendir(path))==NULL) {
perror("opendir");
exit(-1);
}
/*ファイル情報を構造体に格納*/
file_st = (struct filein *)malloc(sizeof(struct filein) *1);
for(dp=readdir(dir);dp!=NULL;dp=readdir(dir)) {
printf("%d ",i);
file_st = (struct filein *)realloc(file_st,sizeof(struct filein) * i+1);
strcpy(file_st[i].filename,dp->d_name);
printf("%s",file_st[i].filename);
printf("%s\n",dp->d_name);
i++;
}
closedir(dir);
}
|