user2302585
user2302585

Reputation: 135

C - freopen() for redirecting needs fclose()?

After a call like freopen(file_name, open_mode, stderr), do I need to call fclose(stderr) before the process ends or it is done automatically ? thanks in advance and sorry for my English

Upvotes: 4

Views: 2629

Answers (4)

phihag
phihag

Reputation: 288090

When a process ends, all its handles are closed automatically. However, it is good style to close every handle you acquire - for example, somebody may want to convert your program to a library, or you may be looking for leaks. Whether you call freopen does not matter for that.

However, in the case of stderr, the situation is a little bit different. Since you didn't specifically open that stream, you shouldn't close it. It's also very likely to be used by other components out of your control, for example atexit functions or stack smashing detection.

Upvotes: 2

ouah
ouah

Reputation: 145899

It is not necessary to close an open stream as all open streams are closed at program termination but it is good practice to have a fclose for every fopen call. In the case of stderr here, this stream is already open at startup (you didn't have to call fopen) and so I see no reason to explicitly close it even if some freopen calls were issued.

Upvotes: 2

yzn-pku
yzn-pku

Reputation: 1082

Of course. And simply fclose(stderr); will do.

Upvotes: 0

Hampus Nilsson
Hampus Nilsson

Reputation: 6822

Yes, that is good practice, but not strictly necessary if your process will end immediately since the OS will clean everything up for you when the process dies.

Upvotes: 0

Related Questions