File Handling In Pascal

From Lazarus wiki
Revision as of 20:45, 16 August 2010 by Cjaster (talk | contribs) (File Handling In Pascal)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

File Handling

Something most programmers need to know how to do is work with files. Files can be used to save user settings,error logs, and more. Here im going to teach you how to work with basic Text Files. First things first.

About Files

When using files in pascal you can use a TextFile type which will allow you to write string into the file, Or create your own file type.

<Delphi> ... Type

TIFile = File Of Integer;//Allows you to write Numbers into the file
TCFile = File Of PChar;//Write PChars into the file :\
TFile = File Os String;//Write Strings into the file

... </Delphi>

If you simply do a file definition it will be impossible to write anything into it. You can write Integers into the TFile we made because its a file of Strings! See? Ok now for Error handling.


IO is the file handling thingy for pascal.. Its what is used for getting errors. Its a compiler directive so you have to do this <Delphi> {$I-}//Turn Off the checking. This way all errors go into the IOResult Variable {$I+}//Turn it back on </Delphi> By disabling(Turning Off) IO it all goes into the IOResult Variable. This is an cardinal type(Numbers). So if you want to write it you have to do the InttoStr Function. Different numbers mean different errors so you may want to check here for the different Error: [1]

File Procedures

There are three file procedures you really need to know about

Rewrite - Is used for creating files

Append - Opens an existing file for editing it

Reset - Opens a file for reading it


So heres a full example of handling a text file with the TextFile Type

<Delphi> Program FileTest;

{$mode objfpc} //Cant forget this ever




 Writeln('File Test');
 AssignFile(FileVar,'Test.txt');//You do not have to put .txt but this is just for now
 Rewrite(FileVar);//Call for Making the file
 Writeln('ERROR! IORESULT: '+InttoStr(IOResult);

end. </Delphi> Now open that file in some text editor and you will see Hello written in it! You can look all over the internet for examples of the Reset and Append Procedures.

Other File Procedures

The SysUtils and some other Units have procedures for making text files.[2]


Making TextFiles in OOP(Object Orientated Pascal) is simple and fast. Mainly because most objects have the SaveToFile procedure.

Much like a TStringList would: <Delphi> Var



 Str := TStringList.Create;
 Str.SaveToFile(<File Path Here>);

end; </Delphi>

Hope I Helped you :D And if anything is wrong or I left something out. Edit At Will!