Fix termination condition for fwrite