File Handling In Pascal

From Free Pascal wiki
Revision as of 07:09, 31 August 2010 by Chronos (talk | contribs)
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 i am going to teach you how to work with basic text files.

Old procedural style

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

<Delphi> ... type

TIntegerFile = file of Integer; // Allows you to write Integers into the file
TPCharFile = file of PChar; // Write PChars into the file :\
TStringFile = file of string; // Write Strings into the file

... </Delphi>

If we only did TFile = File, then it would be impossible to write anything into it! Also, you cannot write integers directly into TFile, because it is a file of strings. Better use the filetype TextFile for writing values of different types.

IO

IO is the file handling thingy for pascal. It is used for getting errors. Since it is a compiler directive, you have to do this: <Delphi> {$I-}//Turn off 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 use the InttoStr function. Different numbers mean different errors. So you may want to check here for the different errors: [1]

File procedures

There are three file procedures you really need to know about

Rewrite - Is used for creating files and editing

Append - Opens an existing file for appending data to end of file and editing it

Reset - Opens a file for reading it

Example

A full example of handling a text file of type TextFile:

<Delphi> program FileTest;

{$mode objfpc} // Do not forget this ever

uses

Sysutils;

var

FileVar: TextFile;

begin

 WriteLn('File Test');
 AssignFile(FileVar, 'Test.txt'); // You do not have to put .txt but this is just for now
 {$I-}
 try
   Rewrite(FileVar);  // creating the file
   Writeln(FileVar,'Hello');
 except
   Writeln('ERROR! IORESULT: ' + IntToStr(IOResult));
 end;
 CloseFile(FileVar);
 ReadLn;

end. </Delphi>

Now open the file in any text editor and you will see Hello written to it!

Heres appending to a file(Editing it)

<Delphi> program EditFile;


{$mode objfpc}

uses

Sysutils;

var

File1: TextFile;

begin

 WriteLn('Append file');
 AssignFile(File1, 'File.txt');
 {$I-}
 try
   Append(File1, 'Some Text');
 except
   Writeln('ERROR IORESULT:' + IntToStr(IOResult));
 end;
 {$I+}
 CloseFile(File1);
 Readln;

end. </Delphi>

Reading a file:

<Delphi> program ReadFile;


{$mode objfpc}

uses

Sysutils;

var

File1: TextFile;
Str: String;

begin

 Writeln('File Reading:');
 AssignFile(File1, 'File,txt');
 {$I-}
 try
   Reset(File1);
   repeat
     Readln(File1, Str); // Reads the whole line from the file
     Writeln(Str); // Writes the line read
   until(EOF(File1)); // EOF(End Of File) The the program will keep reading new lines until there is none.
 except
   Writeln('ERROR IORESULT:', IOResult);
 end;
 {$I+}
 CloseFile(File1);
 Readln;

end. </Delphi>

It is possible to do some file handling using chars instead of strings. This makes it look cool :D.

Other file procedures

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

OOP style

Most of string handling classes have ability to load and save content from/to file. These methods are usually named SaveToFile and LoadFromFile.

Binary files

<Delphi> var

 Buffer: array[0..10000] of Byte;

begin

 with TFileStream.Create('SomeTextFile', fmCreate) do 
 try
   Seek(('Hello');
   Write(Buffer, SizeOf(Buffer));
 finally
   Free;
 end;

end; </Delphi>

Text files

In general for text files you can use class TStringList for loading entire file to memory and have simple access their rows.

<Delphi> begin

 with TStringList.Create do 
 try
   Add('Hello');
   SaveToFile('SomeTextFile.txt');
 finally
   Free;
 end;

end; </Delphi>