0

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.

D. K.
  • 137
  • 10
  • Someone linked this to a post "How do I modify a pointer that has been passed into a function in C?" , in that post there is some guy who wants to add struct to a list of structs, it has nothing to do with this, he uses structs, lists, mallocs, typedef, i have no idea what those are :( – D. K. Mar 12 '22 at 15:56
  • The idea is still the same, you need to pass a `FILE**` as argument and assign to it via `*filepointer =` – UnholySheep Mar 12 '22 at 15:57
  • Someone asked me to reopen the question, i didnt close it, no idea how to do it – D. K. Mar 12 '22 at 16:02
  • as above comment, it's idea to solve your issue, if you still can't, lets create new one, I'll answer more detail. – long.kl Mar 12 '22 at 16:05

0 Answers0