Question

I have a file that I open with fopen in a init function that I leave without closing because I want to fread() it in another function. In order to do this would I declare a global static file that all the functions can interact with?

Was it helpful?

Solution 2

Passing a file through a translation unit - scoped variable (i.e. a static FILE *) is acceptable. However, it leaves some doubts as to who is responsible for calling fclose. A better approach would be to have the function that opens the file return FILE* to the caller, with the assumption that the caller would later call fclose.

Better yet, let the function that calls fread also do the fopen: instead of opening the file, the first function could prepare the file name, and store it in a static variable. Then the reading function could call fopen, do freads, and call fclose all in a single function.

OTHER TIPS

No; you would pass the file pointer to the functions as a parameter.

For example:

FILE *init( char *fname )
{
  FILE *fp = fopen( fname, "r" );
  return fp;
}

void read( FILE *fp )
{
  ...
  while ( fread( buffer, sizeof buffer, 1, fp ))
    // do stuff
}

int main( void )
{
  FILE *fp = NULL;
  ...
  fp = init( "myfile.txt" );
  if ( fp )
    read( fp );
  ...
}

Ideally, functions should communicate through parameters, return values, and exceptions (where available); sharing state through global variables leads to maintenance headaches.

It depends in what scope you need the FILE* that fopen() returns. If you open the file in main(), you can just keep passing the file pointer to other functions as an input parameter. Something like:

int main ( void )
{
    FILE *pFile = fopen ( ... );

    // validate pFile

    SomeFunc ( pFile );

    ...

    fclose ( pFile );
}

void SomeFunc ( FILE *pF )
{
    ...

    fread ( ... );

    ...
}

Unless you really need it for some reason, I wouldn't declare the file pointer as a global variable - it's easy to forget to clean up globals correctly and in larger programs it's hard to see the life cycle of the variable.

The best approach is to keep the scope of the file as tight as possible - this makes it easy to read / maintain the code and releases resources sooner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top