If you want to change what the FILE*
points to, you need to pass a FILE**
. Before you change it, you need to ensure that any file it happens to be pointing to is closed. This also relies on you always setting FILE*
variables to NULL after fclose
(this, alas, does not happen automatically), so there's a decent chance careless use of this function would call fclose
on an already-closed FILE*
. But this is probably still better than willfully leaking file descriptors and not flushing files.
void hello(FILE **fp)
{
// This is actually a horrible test. And in general, this is not
// something you should do, but it is better than leaking open
// file descriptors, so, yeah,
if (*fp != NULL) {
fclose(*fp);
*fp = NULL;
printf("Closed file.");
}
if( (*fp = fopen("log","r") == NULL) {
printf("%s", "Error opening file");
}
}