Need a simple example of passing FILE pointers

Dear friends,

      can anybody pls tell me how to pass FILE pointer in c. I am so confused .. :confused:

suppose I ve two function

  1. file_open()
  2. read_line()

I want to call these function from main() function and in file_open() function it will open that file and in read_line() function I ve take the file pointer from read_line() function then read line by line ..

I tried with code , but I am sure I am doing some stupid stuffs.. Pls Pls help me to get the code right.

FILE* fileopen();
void read_line(FILE*);
 
void read_line(FILE **fh){
      char s[50];
      while(fgets(s,49,fh)!= NULL)
              printf("%s", s);
      fclose(fh);
}
 
FILE* fileopen(){
  FILE *file = fopen("abc1.txt", "r");
  return file;
}
 
int main(void) { 
 
   FILE *fh;
   fh = fileopen();
   read_line(&fh);   
  return 0;
}

If Any other example .. Pls

I should open and close the file in the main function but... try this, change the declaration of the pointer and the call of the read_line function:

FILE* fileopen();
void read_line(FILE*);
 
void read_line(FILE *fh){ ///// change this line
      char s[50];
      while(fgets(s,49,fh)!= NULL)
              printf("%s", s);
      fclose(fh);
}
 
FILE* fileopen(){
  FILE *file = fopen("abc1.txt", "r");
  return file;
}
 
int main(void) { 
 
   FILE *fh;
   fh = fileopen();
   read_line(fh);   //// change this line
  return 0;
}

Regards

Really many many Thanks for the help .

I ll neva forget this..

IS there any problem if I omit the line fclose(fp); if the fp is open .

If yes what ll be the problem..

It's usually to close the file after using it so the pointer can be used to access a different file.
If files are still open when a program exits, the system will close them. However it is usually better to close the files properly.
Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it.

Regards

Thank you very much .. I got it now..

Your FILE pointer programme helped me a lot for my project..
Thanks again..
GOD bless You..

Regards,
user_prady