I have a function that takes in a filename (string) and I want to have an array of filenames (strings) to check to see if the filename taht was passed in is in the array and if not add it to it. Here is what I got so far.
bool read_file(char * filename, bool warnings){
//Check to see if filename is in array files
static char * files[MAXFILES];
static int counter = 0;
for(int i=0;i<counter;i++){
if(strcmp(filename,files[i]) == 0){
fprintf(stdout, "Error\n");
return 0;
}
else{
files[counter]=filename;
counter++;
}
}
FILE * fp = fopen(filename,"r");
if(fp == NULL){
if(warnings){
fprintf(stderr, "Can't open the file %s\n",filename);
return 0;
}
else{
return 0;
}
}
else{
fclose(fp);
fp = NULL;
return 1;
}
}
For some reason it wont add filenames to files[] any help would be appricated.
Take a look at the first time through your loop (when
i == 0andcounter == 0):i < counteris always false, becausecounteris incremented in the body of the for loop.You’ll need to rethink your logic. This function is doing a lot of stuff. Maybe something like this infront of the loop will help:
However, you might have better luck splitting this into a couple functions. One to add a filename to the array, another to check if it’s already there, a third to open the file, etc.