Reputation: 137
So basically i need to declare file pointer in main functions, and use it in multiple sub-functions, file will be opened in sub function.
int main(){
FILE *filepointer;
function print(filepointer);
function count_line(filepointer);
}
now in function_print i do basic print whats inside the file, i dont close the file, because it will be done in the next function, and both function have to be done in sequence.
void print(FILE *filepointer){
filepointer = fopen("example.txt", "r+");
char ch;
while(ch != EOF){
ch = fgetc(filepointer);
printf("%c",ch);
}
}
now in second function i have to reset the file pointer to the beggining and count how many lines in file
void count_line(FILE *filepointer){
fseek(filepointer, 0, SEEK_SET);
int counter=0;
char ch;
while(ch != EOF){
ch = fgetc(filepointer);
if(ch == '\n'){
counter+=1;
}
}
printf("Number of lines = %d",(counter);
fclose(filepointer);
}
I tried using rewind() rather than fseek, but it didn't help. The print function works normally, I don't get any errors or warnings. But the count_line function doesnt work, it just prints
Number of liner = 0
Thank you for any help. Honestly i think its gonna be some ** or * problem within the print function, maybe it doesn't change the value in main or something, but i tried doing it with double pointer and i couldn't get it right. Thank you.
Upvotes: 0
Views: 20