Why can't I read what is in a directory, it keeps on giving me segmentation faults?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int count(char* loc)
{
int num = 0;
char c;
FILE *file = fopen(loc, "r");
while( (c = fgetc(file)) != EOF) {
if(c == '\n')
num++;
}
int r = fclose(file);
return num;
}
int main()
{
int lines = 0;
int files = 0;
char* names[files];
int i = 0;
DIR* d = opendir("./visual"); //You can change this bit
struct dirent *file;
while((file = readdir(d)) != NULL){
i++;
names[i] = file->d_name;
files++;
printf("%s\n", names[i]);
}
closedir(d);
printf("__________\n");
for(int i = 0;i < files;i++){
printf("i = %d\n", i);
lines = lines + count(names[i]);
}
printf("you have written %d lines of code", lines);
}