I need to write a function that will recursively display the contents of files whose names are contained in the first file. Additionally, I want the function to return the number of opened files.
eg.
first.txt:
pull.txt
predict.txt
suppress.txt
mount.txt
transfer.txt
predict.txt:
constitute.txt
determine.txt
swim.txt
Result:
pull.txt
predict.txt
constitute.txt
determine.txt
swim.txt
suppress.txt
mount.txt
transfer.txt
Number of files: 2
So far I have managed to display the files, but I have no idea how to return the number of files.
int read_file(const char *filename){
if(filename==NULL){
return 0;
}
FILE *file;
char tempName[31];
if((file= fopen(filename,"r"))==NULL){
return 0;
}
while (!feof(file)){
fgets(tempName,31,file);
tempName[strcspn(tempName, "\n")] = 0;
printf("%s\n", tempName);
read_file(tempName);
}
return 1;
}
P.S. I'm just starting to program, so please forgive me if my code is simple or poorly secured. This is part of an assignment that just needs an idea of how to execute and that's what I'm missing :) Thanks for any advice given in the comments.
I found the solution, thanks for all the hints :)
int read_file(const char* filename){
if(filename==NULL){return -1;}
FILE* file;
char buffer[31];
int counter=0, res;
if((file= fopen(filename,"r"))==NULL){return -1;}
while (!feof(file)){
fgets(buffer,31,file);
for (size_t i = 0; i < strlen(buffer); ++i) {
if(*(buffer+i)=='\n'){*(buffer+i)=0;}
}
printf("%s\n", buffer);
res= read_file(buffer);
if(res!=-1){
counter+=res;
}
}
fclose(file);
return counter;
}