tmighty
tmighty

Reputation: 11399

C++ Pass FILE * as argument to a function

I want to pass a FILE * to another function. In this function some bytes are read from the file using fread. No writing is performed.

I was wondering if I should say

void DoSomething(FILE *uFile)

or

void DoSomething(const FILE *uFile)

I was afraid to introduce a memory leak somewhere and thought that maybe const be safer. I was afraid that the function might create a copy of the file or so when I pass it improperly.

I create FILE * like so:

FILE *outfile  = fopen("c:\\myfile.dat", "wb");

Thank you.

Upvotes: 1

Views: 3465

Answers (3)

Dinesh
Dinesh

Reputation: 1866

You can go with:

void DoSomething(const FILE *uFile)

No duplicate of the file is created.

Upvotes: 0

bmargulies
bmargulies

Reputation: 100050

C++ will never copy an object when you pass a pointer to that object as a parameter. Const is not there to make statements about copying, it is there to make statements about modification. So you need not worry about leaks. As others have pointed out, all the functions that take FILE* take it non-const, so you'd only have to cast it away, anyway.

Upvotes: 1

abelenky
abelenky

Reputation: 64682

Whatever function you pass your FILE* to, is eventually going to call some variant of fread / fscanf / fwhatever. If you look, ALL of those functions take a (non-const) FILE*.

You need to be prepared to give those functions what they require. If they're prototyped to take a non-const parameter, and you try to give them a const parameter, you'll get a compiler warning.

For this reason, I would pass in a non-const FILE*

Upvotes: 4

Related Questions