views:

117

answers:

2

Is this the correct syntax for passing a file pointer by reference?

Function call: printNew(&fpt);

printNew(FILE **fpt)
{        
   //change to fpt in here kept after function exits?
}

Thanks.

+4  A: 

No. The correct syntax is

void printNew(FILE *&fpt)
{        
   //change to fpt in here kept after function exits?
}

Your code will only change the local pointer to a FILE pointer. Only changes to *fpt are seen by the caller in your code. If you change it to the above, things are passed by reference and changes are promoted like intended. The corresponding argument is passed as usual

printNew(fpt);
Johannes Schaub - litb
@Tommy Your acceptance of this (correct for c++) answer leaves us no clearer if the this question is actually about C++, or C.
anon
@Tommy why have you accepted my answer, but retagged your question to C? That makes no sense to me.
Johannes Schaub - litb
@Johannes: re-tag to C was a error, changed back to C++ as intended.
Tommy
+2  A: 

I'd be interested in what you are going to do with that file pointer - the normal things you do on an open pointer are to call functions like fgets() and close it with fclose(), none of which require a reference.

anon
Close the file, and open a new one with that pointer. Reference not needed?
Tommy
@Tommy If you need the newly opened file to be accessible after the function returns, then yes. But I think I might to make the function return the new pointer as its return value.
anon
@Tommy I meant of course - "then yes, reference needed". But I'd still prefer a return value.
anon