So im writing a program to open a directory, get all the files inside, and then read the contents of each file. currently i successfully got all the file names in a string array. the print files[] loop shows all the file names, but the loop to check frequency does not read the files correctly. how do i successfully read an array of file names and then scan each of their contents?
//Open Directory
DIR *dr = opendir(path);
struct dirent *de;
if(dr == NULL){
printf("Could not open directory");
return 0 ;
}
const char* files[100];
int buffer=0;
//Read Directory Files
while((de = readdir(dr)) != NULL){
files[buffer] = de->d_name;
buffer++;
}
for(int x = 0; x <= buffer; x++){
printf("%s" , files[x]);
}
closedir(dr);
//Check Frequency
for(int i = 0; i <= buffer; i++){
int ch;
FILE *fp;
fp = fopen(files[i], "r");
if(fp == NULL)
continue;
ch = fgetc(fp);
while(ch != EOF){
ch = tolower(ch);
if(ch>=97 && ch<= 122){
alphabetfreq[ch-97]++;
}
ch = fgetc(fp);
}
fclose(fp);
de->d_nameto your array.de->d_nameis an internal variable and likely reused byreaddir. You should allocate for each name and store the name instead of a pointer tode->d_namealphabetfreq[]definition and much else missing. Review minimal reproducible example.and..file names. The posted code is missing the check for symbolic links