まず、dirent構造体は使いまわしされることがあるので、
文字列へのポインタをそのまま代入するのではなく、新しい領域を確保して文字列をコピーするべきです。
そして、ファイル名としてfile_nameではなくfile_name[i]を使用して処理をするべきです。
また、file_name[i]にはファイル名しか含まれていないので、
ディレクトリ名を追加してあげないと対象のディレクトリではなくカレントディレクトリからファイルを読もうとしてしまいます。
さらに、下のfor文においてfile_name[cnt]は初期化されていないので、アクセスしてはいけません。
最後に、操作を続行する前にopendirやfopenが成功したかをチェックするべきです。
コード:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#define N 100001
int main(){
DIR *dir; //ディレクトリポインタ
struct dirent *dp; //dirent構造体
char path[256] = "./source"; //指定ファイルへのパス
char *file_name[N];
char file_content[N];
int cnt = 0;
FILE *fp;
dir = opendir(path); //指定パスのディレクトリopen
if(dir == NULL){
perror("opendir");
return 1;
}
// ディレクトリ読み込み
for(dp=readdir(dir);dp!=NULL;dp=readdir(dir)){ //ディレクトリ内に要素が無くなると、nullが返る
file_name[cnt] = malloc(strlen(dp->d_name) + 1);
if(file_name[cnt] == NULL){
perror("malloc");
for(int i=0; i<cnt; i++){
free(file_name[i]);
}
return 1;
}
strcpy(file_name[cnt], dp->d_name);
cnt++;
}
for(int i=2; i<cnt; i++){ //ディレクトリ読み込み時,"."と".."も読み込まれているのでi=2から始める
char* file_path = malloc(strlen(path) + 1 + strlen(file_name[i]) + 1);
if(file_path == 0){
perror("malloc");
continue;
}
strcpy(file_path, path);
strcat(file_path, "/");
strcat(file_path, file_name[i]);
fp = fopen(file_path,"r");
free(file_path);
if(fp == NULL){
perror("fopen");
continue;
}
while(fgets(file_content,64,fp) != NULL){
printf("%s",file_content);
}
fclose(fp);
}
closedir(dir);
for(int i=0; i<cnt; i++){
free(file_name[i]);
}
return 0;
}