9 years, 5 months ago.

What is a proper interval between repeated open/close of a file handle?


I am working on a data logging type of application which requires repeated open and close of certain file. If I run the following code, system crashes in almost no time:

while (1) {

if I put delay between each cycle, like 1 or 0.5 seconds, then the application runs perfectly fine for as long as I let it run. So my question is: what would be an acceptable range of delay between each fopen/flose cyle?

I am thinking of using a ticker to handle fopen/fclose and let the main thread handle fprintf.

update: I eventually ended up using an arbitrary interval of 1 minute. A dozen of my LPC1768 based testing units have been running for months now, and none of them have had any SD card related incidents.

Question relating to:

4 Answers

9 years, 5 months ago.


what target do u use? What does it mean: system crashes? ffprintf is buffered, which means that it might happen that your app closes the file before all data have been written.

Can you add fflush after fprintf, if that does help?

Target: I use LPC1768. it is a customized board. Connection to SD card is the same as the one outlined in cookbook except a 0.1uF capacitor on VCC close to SD card socket.

Crash: I mean the whole MCU hangs. I have a LED blinking outside fopen/flcose cycle. As soon as I start feeding data, LED stops blinking, stays either on or off.

fflush(): I didn't try this. There are a few posts on the forum stating fflush doesn't really force writing. http://mbed.org/questions/3984/SDFileSystem-and-fflush/ http://mbed.org/questions/128/Forcing-a-write-to-a-file-on-a-SD/ I will try it later.

posted by Zhiyong Li 18 Sep 2014
9 years, 5 months ago.

Hello Zhiyong Li,

maybe I am wrong but in my oppinion it would be better to not again and again open write and close file in while(1) loop. For me it seems better to open file once (maybe in main() and then only fprintf(); in while loop. So you will need some logic to open and close file once per logging period.

I have the same feeling with you: repeatedly open/close a file doesn't sound right. But that seems the only way to ensure/force write of each new line to log file. As pointed out by Martin Kojtal, fprintf is buffered. Other users stated that fflush seems not working properly somehow.

My log period is a day, I am thinking of either poll the date before each entry of new data or use a ticker to check the date and open/close a file every 530 minutes.

posted by Zhiyong Li 18 Sep 2014
8 years, 9 months ago.

I confirme, i have a memory leak with fclose() with a nucleo-l152re.