I am having a weird issue with this C program I'm writing to loop through a directory and open each file to do some work on. My program is located in the parent directory of the directory I'm searching through. In order for fopen to be able to see the files in that directory I am making a chdir(path) call right before my while((dp = readdir(dfd)) != NULL) call. The first file gets picked up fine but I get a segfault for the next iteration on this call. It seems to be a problem with the chdir and readdir logic and I'm not sure how to fix it. Any ideas? Here is my code:
if((dfd = opendir(dir)) == NULL){
fprintf(stderr, "Can't open %s\n", dir);
return 0;
}
chdir(dir);
char *filename;
//loop through the directory
while((dp = readdir(dfd)) != NULL){
printf("Searching file %s\n", dp->d_name);
filename = malloc(50);
filename = dp->d_name;
char text[80];
int words = 0;
int cellular = 0, CDMA = 0, GSM = 0, LTE = 0, wireless = 0, realtime = 0, GPS = 0, remote = 0, monitor = 0;
struct stat stbuf;
//Skip any directories
if((stbuf.st_mode & S_IFMT) == S_IFDIR){
printf("Directory skipped.\n");
continue;
}
//Skip files that can't be opened
if((fpt=fopen(filename,"r")) == NULL){
printf("Couldn't open file %s.\n", filename);
continue;
}
//search the file
while(fscanf(fpt, "%s", text) != EOF){
words++;
//....etc