Wednesday, 2 February 2011

Pascal Lesson 10 - Text Files

Learn Pascal Programming Tutorial Lesson 10 - Text Files

You should by now know that a text file is a file with lines of text. When you want to access a file in Pascal you have to first create a file variable.
program Files;

var
   f: Text;

begin
end.

After the variable has been declared you must assign the file name to it.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
end.

To create a new empty file we use the Rewrite command. This will overwrite any files that exist with the same name.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rewrite(f);
end.

The Write and Writeln commands work on files in the same way they work on the screen except that you must use an extra parameter to tell it to write to the file.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rewrite(f);
   Writeln(f,'A line of text');
end.

If you want to read from a file that already exists then you must use Reset instead of Rewrite. Use Readln to read lines of text from the file. You will also need a while loop that repeats until it comes to the end of the file.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Reset(f);
   while not eof(f) do
      Readln(f,s);
end.

Append opens a file and lets you add more text at the end of the file.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Append(f);
   Writeln(f,'Some more text');
end.

No matter which one of the 3 access types you choose, you must still close a file when you are finished using it. If you don't close it then some of the text that was written to it might be lost.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Append(f);
   Writeln(f,'Some more text');
   Close(f);
end.

You can change a file's name with the Rename command and you can delete a file with the Erase command.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rename(f,'YourFile.txt');
   Erase(f);
   Close(f);
end.

To find out if a file exists, you must first turn off error checking using the {$I-} compiler directive. After that you must Reset the file and if IOResult = 2 then the file was not found. If IOResult = 0 then the file was found but if it is any other value then the program must be ended with the Halt command. IOResult loses its value once it has been used so we also have to put that into another variable before using it. You must also use {$I+} to turn error checking back on.
program Files;

var
   f: Text;
   IOR: Integer;

begin
   Assign(f,'MyFile.txt');
{$I-}
   Reset(f);
{$I+}
   IOR := IOResult;
   if IOR = 2 then
      Writeln('File not found');
   else
      if IOR <> 0 then
         Halt;
   Close(f);
end.

No comments:

Post a Comment