Thread: file pointer as an argument?

  1. #1
    Unregistered
    Guest

    Question file pointer as an argument?

    hello,

    When we pass int pointer or char to a function, we do something like this:

    main()
    {
    pass(&i,&c);
    }

    void pass(int *i, char *c)
    {
    .........................
    }

    Question:
    How do I pass a file pointer that is opened in the main function to another function as an argument? After passing the file pointer to the function, do I need to close the file i.e fclose(fp) at the end of that function, eventhough, there is fclose(fp) in the main function?

    Please help!

  2. #2
    Unregistered
    Guest
    FILE*fp = fopen("myfile.txt","r");
    myfunction( fp );


    where:

    void myfunction( FILE* fp )
    {
    ... do stuff here...
    }



    Quzah.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    21
    You should be able to close the file from your main() function or your other function, I don't think it really matters WHERE you close it, as long as you make sure it gets closed...

    (:

  4. #4
    Unregistered
    Guest
    Additionally, if you try and close a file that has been closed, you may end up with fun errors / unexpected results.

    I use this rule of thumb: Close the file where you open it.

    Exceptions to this would be if you were trying for OO design and had open and close methods.

    Quzah.

  5. #5
    Unregistered
    Guest
    Let me clarify that: Close the file in the same block / function you open it in. That is to say:
    Code:
    void myfun( FILE* fp )
    {
       fclose( fp ); //bad, IMO
    }
    
    void myfun2( char *s )
    {
       FILE*fp=fopen( s, "r" );
       //do stuff here
       fclose( fp );
    }
    
    int main( void )
    {
       FILE*fp=NULL;
       fp = fopen( SomeFileHere, "r" );
       //do stuff here
    
       myfun( fp ); //bad, IMO
    
       myfun2( "SomeFile" ); //good IMO
    
       fclose( fp ); //good, IMO
    }
    Quzah.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  3. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  4. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM