Prevent writing the same file several times (fixes #3753)