You didn't say which operating system you're on, and the implementation details differ. But in general file systems just aren't atomic so these things are difficult, and they never work on network file systems.
However, you might find it easier to split this into 2 files, one just for the locking that you never need to remove so there's no race, and the other one for the data.
# pseudo code :)
# of course you need to read the counter under the lock too
As long as everyone who accesses the counter uses the lock you should be ok