Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to fclose() both files after freopen()? [duplicate]

Tags:

c

fopen

freopen

I'm writing a code which takes one file and saves it into another with a different name - however, I am not sure whether or not I need to fclose both files or not?

FILE *logfile = fopen("log.txt", "a+");
while(1) {
    char filename[500];
    char logline[512]; 
    char channel[512];

    //Do stuff

    sprintf(filename, "%s.log.txt", channel);
    freopen(filename, "a+", logfile);
    log_to_file(logline, logfile);
}
like image 650
Daniel Avatar asked Sep 16 '25 03:09

Daniel


1 Answers

From the man page

The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. [...]

So, you don't need to close the previous stream explicitly, once done usage, just close the recent stream.

like image 162
Sourav Ghosh Avatar answered Sep 17 '25 20:09

Sourav Ghosh