If two threads will execute your code almost simultaneusly with the small delay, the 1st thread will open file for write and erase it contents before locking.
The 2nd thread will read the empty file contents, wait for lock release, and then overwrite the correct data.
The solution is to open file not in "w", but in "a" or "c" mode and then use fwrite, fseek and ftruncate.