Search code examples
cstringfopenprintfformatted

reading fprintf while the program is running


So I'm writing a program that is suppose to run forever (client server stuff) in C, and I'm writing to a log. I am using fopen and fprintf to be able to write to the file. My problem is that since the program is suppose to run forever, there really is no point where I can put a fclose. And when I Ctrl+C to stop the process, and the log file, it shows nothing? I want to use fprintf because it allows me to have formatted strings, is there a way for me to log my output while still having formatted strings?


Solution

  • What's happening is that the output is being buffered and when the program is killed, the buffer is never flushed to disk. You can either periodically flush the buffer (fflush), or you can try to capture the kill signal. Specifically, Control + C sends the SIGINT signal, so you'd need to register a handler for that.

    As to minimize potential buffer loss, I would probably use both strategies.

    How can I catch a ctrl-c event? (C++)

    Edit: As Adam said, you can also just open and close the file when necessary, but depending on how frequently you're writing, you may want to keep the file open in which case my answer would apply.