until now, whenever I wanted to create a file without overwriting an existing one, I’ve done something like this:
if not FileExists(filename) then
stream := TFileStream.Create(filename, fmCreate);
But that’s not threadsafe. So now I am looking for a threadsafe version.
Perhaps I can combine some modes so that TFileStream.Create(filename, fmCreate +fm???); fails if the file exists?
I need this to communicate directory-locks with old DOS programs. But the DOS programs don’t hold the files opened. 🙁
TFileStream‘s file-name based constructor relies on the WIndows API call CreateFile to create the file handle that’ll be used to access the file. The API itself has multiple parameters, and especially interesting for you is the Create Disposition: if you specifyCREATE_NEW, the function fails if the file already exists. You can take advantage of that by callingCreateFileyourself, then using the returned handle to create theTFileStream. You can do that becauseTFileStreaminherits fromTHandleStream, inherits it’s handle-based constructor and owns the handle (callsCloseHandleon the handle you pass to the constructor).Since this relies on the OS-provided function
CreateFile, it’ll be trehad-safe (no race condition betweenFileExists()and actually creating the file. It also blocks the old application from accessing the newly crearted file until you actually close the handle.