Delphi
Basics - Reading and Writing Files
Generic File I/O methods:
- Delphi has 3 main approaches to read/write of generic
files:
- Old Pascal File
I/O:
- this is a low-level approac & uses
the old 'file variables' depending on the
file:
- untyped
files:
- any data type eg. binary
data, text, wav files
- declared as: var F: File;
- the Reset and Rewrite
procedures allow an extra
parameter to specify the
record size used in data
transfers. For historical
reasons, the default
record size is 128 bytes.
A record size of 1 is the
only value that correctly
reflects the exact size
of any file.
- Except for Read and
Write, all typed-file
standard procedures and
functions are also
allowed on untyped files.
Instead of Read and
Write, two procedures
called BlockRead and
BlockWrite are used for
high-speed data
transfers.
- Text
files:
- this allows you to
read/write/create ascii
text files
- declared as T:Text;
- example of reading an
existing text file:
- var F:
System.Text;
S,S1,S2,S3,S4: String;
i:Integer;
- begin
- System.assign(F,
'MyFile.Txt');
- Reset(F);
//open existing file -
can also use append(F)
to open a file and append
text
- ReadLn(F,S1,S2,S3,S4);//this
reads current line and
1st 4 "words"
would be divided into
S1,S2,S3,S4
- ReadLn(F,i); //reads
the next line entirely
into the integer variable
i (hopefully the line is
an integer)
- While not EOF(F)
do
- ReadLn(F,S);
// reads the next line
entirely into S variable
- System.Close(F);
//free resources
- end;
- example of writing a new
text file:
- var F:
System.Text;
S,S1,S2,S3,S4: String;
i:Integer;
- begin
- System.assign(F,
'MyFile.Txt');
- Rewrite(F);
//create new file or
over-write one if already
exists
- WriteLn(F,S1,S2,S3,S4);//writes
S1+' '+S2+' '+S3+' '+S4
to next line
- WriteLn(F,i); //writes
the the integer variable
i to the next line
- System.Close(F);
//free resources
- end;
- typed
files:
- Reading
and Writing Records
to ASCII text file:
- you can store
records in a text file as
follows:
- var MyRecFile: File
of
MyRec; MyRec1: MyRec; //where
MyRec is a record
variable
- begin //this
is similar to read/write
of a textfile
- Assign(MyRecFile,
text filename);
- Reset(MyRecFile);
//opens text file
nb. use
rewrite(MyRecFile) to
create a new file or
overwrite
- while not
EOF(MyRecFile) do
- Read(MyRecFile,MyRec1);//read
all records nb. use
write(MyRecFile,MyRec1)
to write.
- Close(MyRecFile);//close
reference to physical
file
- end;
- Windows API
encapsulation:
- not recommended as not compatible with
Pascal File I/O routines
- var FileHandle : Integer;
- begin
- FileHandle :=
FileOpen(FileName, fmOpenWrite or
fmShareDenyNone);
- if FileHandle > 0 then
[valid file handle]
- else [Open error: FileHandle
= negative DOS error code]
- end;
- File streams:
- File streams are object instances of the
VCL TFileStream class used to access the
information in disk files.
- File streams are a portable and high
level approach to file I/O.
- TFileStream has a Handle property that
gives you access to the Windows file
handle.
- TFileStream can interact easily with
other stream classes. For example, if you
want to dump a dynamic memory block to
disk, you can do so using a TFileStream
and a TMemoryStream.
- To create or open a file and get access
to a handle for the file, you simply
instantiate a TFileStream. This opens or
creates a named file and provides methods
to read from or write to it. If the file
can not be opened, TFileStream raises an
exception.
- var fs:TFileStream;
- begin
- fs :=
TFileStream.Create(filename,Mode);//mode
= (fmCreate,
fmOpenReadWrite, etc)
- [read/write/readBuffer/writebuffer
methods can be used]
- fs.free;
- end;
- you can create streaming audio over
networks using this see Delphi Informant
"NetSound"
Reading and Writing Ini Files:
- ini files are the old Win 3.1x method of storing
application settings and have a format of:
- [sectionName]
- itemName=itemValue
- Delphi includes a component helper class called TIniFiles
to assist reading & writing this format:
- uses IniFiles;
- var ini:TiniFile;S:String; i:Integer;
B:Boolean;
- begin
- ini :=
TIniFile.Create('iniFileName.ini');
//default directory is Window's
directory!!
- try
- S :=
ini.readString('SectionName','itemName','DefaultValueIfNotFound');
- i :=
ini.readInteger('SectionName','itemName',DefaultIntegerValueIfNotFound);
- B :=
ini.readBool('SectionName','itemName',DefaultBooleanValueIfNotFound);
- ini.writeInteger('SectionName','itemName',i);
//writes a value
- finally ini.free; end; //free
resources
Reading and Writing Windows
Registry:
- Delphi provides two methods for doing this:
- TRegIni:
- this makes it easier for programmers used
to the TIniFiles method
- TRegistry:
Reading and Writing via Visual
Components:
- various components allow you to read data from files and
write to files, for example:
- All components:
- can read/write their own persistence
properties via streams
- TMemo, TDBMemo:
- can read/write ascii text files
via Memo1.Lines.LoadFromFile('filename');
and SaveTofile('filename');
- you can also read/write a memo datafield
via streams using TBlobStream:
- var bs: TBlobStream; dest:
TStringList;
- begin
- bs :=
TblobStream.create(TMemofield(MyMemofield),bmReadWrite);
- try
- dest.LoadFromStream(bs);
//stream memo into dest
- bs.write(dest.GetText^,StrLen(dest.GetText));
//you can write back
to bs
- finally bs.free; end;
- end;
- TRichEdit, TDBRichEdit:
- can read/write rich text
formatted ascii text files as
for TMemo method.
- can read/write to RTF stream
via LoadFromRTFStream(stream);
- TImage, TDBImage:
- can read/write image files
(BMP,WMF, JPG) via Image1.Picture.LoadFromFile('filename'),
etc.
- TMediaPlayer:
- can open any mci media file
(eg. WAV, AVI) via:
- MediaPlayer1.Filename :=
'filename';
- MediaPlayer1.open; //open
file in media player which has
buttons for play, record, etc.
- MediaPlayer1.play; //play
the file
- MediaPlayer1.close;
//free resource
- TOleContainer:
- can open/save OLE objects
- TQRPreview:
- can create/open/save Quick
Reports
- if use QRFilters can save as
ASCII text, HTML
- TChart:
- can read/write TeeChart templates
and apply new template to chart via LoadChartFromFile..
- TDatasets in general:
- can read/write almost any database
format if drivers are installed,
including ASCII text databases
- TSession:
- can read/write BDE configuration
file eg. GetAliasParams(aliasname);
ModifyAlias(aliasname, params);
- TQuery:
- can read/write SQL text file
via Query1.SQL.loadFromFile('SQLFile');
etc
- TClientDataset:
- can read/write CDS formatted text
files (Borland text database
format)