4

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);
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Daniel
  • 47
  • 5
  • When the program ends both files will be automatically closed, so it is not extrictly necessary, but yes recommendable – EUS May 29 '19 at 08:26
  • 1
    You can have multiple files opened at the same time, just make sure you close them at some point.(if some other program tries to access the files you are reading/writing problems might arise) If you are %100 sure no one else uses these files, do whatever you want. – Mete Han Kahraman May 29 '19 at 08:27
  • 1
    `freopen` closes the original file, and associates the given `FILE` pointer with the new file. Which means that the code only has one file open at a time, and therefore only one file to close. And yes, it is good practice to close a file when you're done with it. – user3386109 May 29 '19 at 08:50
  • @user3386109 Perfect! That's exactly what I couldn't confirm - I wasn't sure if the old pointer still needed to be closed or not. Thank you! – Daniel May 29 '19 at 08:52

1 Answers1

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261