Delphi: create or append to a TFileStream
Posted by jpluimers on 2018/08/23
It looks like the Delphi [WayBack] TFileStream.Create does not have an overload that allows you to create or append. Luckily, [Archive.is] TFile.Open allows you to do this when passing the correct [Archive.is] TFileMode enumeration value:
TempStream := TFile.Open(TempPath, TFileMode.fmOpenOrCreate, TFileAccess.faReadWrite, TFileShare.fsRead);
I still wonder why that never made it into a TFileStream.Create overload, or why these overloads fail to use enumerations or sets of modes.
–jeroen






HeartWare said
Another shameless plug :-) :
This prompted me to make a UNIT that has an interposer class that re-defines TFileStream (inherits from original TFileStream) and introduces new fmAppend and fmAppendExisting file open modes. The UNIT can be downloaded from my home page:
http://www.heartware.dk/HeartWare.FileStream.7z
fmAppend will create the file if it doesn’t already exists (like fmOpenCreate) and fmAppendExisting will fail if the file doesn’t already exist (like fmCreateNew).
It should be a plug-in replacement for the TFileStream with support for the new file modes. In Append modes, the file is (by default) opened in WriteOnly, ShareDenyWrite mode and seek’ed to EOF upon open. You can, however, specify specific access and sharing modes.
There is also an easy interface to write text to the file (since the most uses for an Append mode will be log files), with an internal TTextWriter accessible via TW function, and directly implemented for easy access of two WriteLine methods directly in the new TFileStream (it just passes the arguments on to the internal TTextWriter).
The code is under CC (Creative Commons) license CC-BY-SA – see https://en.wikipedia.org/wiki/Attribution_(copyright) and https://en.wikipedia.org/wiki/Share-alike for info.
jpluimers said
Thanks! Now put it on github for easier sharing and versioning (;
HeartWare said
Don’t know how :-).
HeartWare said
I figured it out. It is now available here:
https://github.com/HeartWareDK/TFileStream/
Thomas Mueller said
shameless plug:
https://osdn.net/projects/dzlib-tools/svn/view/dzlib/trunk/src/u_dzFileStreams.pas?view=markup&revision=699&root=dzlib-tools
Remy Lebeau said
Internally, TFile.Open() first calls TFile.Exists() and then constructs the TFileStream using fmOpen… (according to the Access parameter) or fmCreate accordingly. Same as everyone else who ever constructs a TFileStream directly.