Last Updated:

Working with files in Pascal: overview

Working with files in Pascal: overview

The Pascal language highlights file data that is used to work with information on external devices. This information is embedded in the computer's memory, forming a certain area, which is called a "file".

A file is a collection of similar elements. It has a name(s). Most often, files are used when long-term storage is needed, a large amount of data or for the purpose of providing access by several devices to a single content.

Files are classified into logical and physical. The latter are located on removable media and they are given a name. Logical ones are presented in the program.

 

The Pascal language contains 3 kinds of files:

 

  1. Text.
  2. Typed files (fileof<type>);
  3. Typeless or untyped (file).

Describes file variables. Example:

var
f1: fileofchar;
f2: fileofinteger;
f3: file;
t: text;

Standard procedures and functions

All disk files become available to the program after they are associated with their file variable declared in the program. Any operations in the program are performed only with the help of a file variable associated with a physical file.

Assign(f, FileName)

Responsible for linking the file variable f to the file whose name is specified in the FileName line. This link will be continuous until the program is terminated or until the reassignment occurs.

When a file variable is bundled with a file name in the program, you must specify the direction of data transfer. Depending on this direction, they talk about writing to a file or reading from a file.

Example:

Assign (chf, ‘G:\Home\ Student\ Lang\ Pascal\ primer.dat’);

Reset(f)

Opens the file for reading, with which the file variable f is linked. After you run the Reset procedure, the file is ready to read the first element from it. If the specified file is not found, the Reset procedure will complete with an error message.

In the event that f is a typed file, it is opened for reading and writing at the same time.

Rewrite(f)

The procedure opens a file for writing, with which the file variable f is linked. After you run the Rewrite procedure, the file is ready to be written. If such a file already existed, the data will be overwritten.

Example:

Rewrite(<name_f_variable>);

Close(f)

The procedure closes a previously opened file with the file variable f. The procedure is required when you finish working with the file. If it is not executed, the file will still be created on the external device, but the contents of the last buffer will not be transferred to it.

Example:

Close(<list of file variables>);

EOF(f): boolean

The procedure returns TRUE when the end of the file is reached during reading. This means that the last element in the file was read or it was empty.

Rename(f, NewName)

The procedure allows you to rename the file on the disk that is associated with the file variable f. You can specify a new name only after you close it.

Erase(f)

The procedure destroys the physical file that is associated with the file variable f. The file should have been closed by the time the procedure is called.

IOResult

The procedure returns an integer that corresponds to the last I/O error code. If the operation completes normally, IOResult will return a value of 0. The value of the function must be assigned to a variable, because each time the function is called, it will reset its value. IOResult works with the compilation key {$I-}or when the input error checking mode is turned off.

Working with text files

What is a text file? In fact, it is a set of formations that are separated by labels of the end of the line. The file ends with the end of the file label. Each line is accessed only sequentially, starting with the first. Reading and writing at the same time are prohibited.

To read a text file:

Read(f, list of variables);

ReadLn(f, list of variables);

Procedures read information from file f into variables. The type of variables in the list determines how you read it. Characters from the file are placed in the char variable. The numeric variable ignores leading spaces and delimiters, and reads the value of the number up to the next delimiter.

The number of characters corresponding to the length of the string is placed in a variable of type string (and then only if the characters of the end of the file or the end of the line have not previously met).

What is the difference between Read and ReadLn? In the first procedure, after reading the data, all other characters in a given line, including the end label of the string, are skipped. If there is no list of variables, ReadLn(f) skips the posting of the text file.

Writing to a text file:

Write(f, list of variables);

WriteLn(f, list of variables);

These procedures write information to a file. How you write it depends on the type of variables in the list. The output format is taken into account.

The WriteLn procedure, unlike Write, after writing all the values from the variables, writes to look for the end of the line label (a completed line of the file is created).

Add information to the end of the file:

Append(f)

This procedure opens a text file to add information to the end of the text file. This procedure is used instead of Rewrite.

Working with typed files

 

What is a typed file? This is a sequence of components of any specified type (except for the "file" type). The components of the file are accessed by their sequence numbers. Numbering starts with 0. The number of the current component (pointer) after opening the file is at the beginning of the file on the zero component. After each write or read, the pointer will shift to the next component.

Writing to a file:

Write(f, list of variables);

This procedure writes information from a list of variables to file f.

Write(<name_of_a_variable>, <list of a record>);

Reading from a file:

Read(f, list of variables);

The procedure reads the components from file f to the specified variables. The type of variables and file components must match. When you try to read a component that does not exist, the program will quit incorrectly. You need to accurately calculate the number of components or check their existence before each reading.

File pointer offset:

Seek(f, n);

Moves the pointer to file f to the specified position (n). Numbering in a file is counted from scratch.

To determine the number of components:

FileSize(f): longint;

The procedure returns the number of components in file f.

Determining the position of the pointer:

FilePos(f): longint;

Returns the sequence number of the current component of file f.

To cut off the last components of the file:

Truncate(f);

The function cuts off the end of the file (from the current position inclusive).

Working with untyped files

Untyped files are a sequence of components of an arbitrary type.

To open an untyped file:

Reset(f, BufSize)

Rewrite(f, BufSize)

BufSize specifies the number of bytes that are written to or read from a file in a single hit. The maximum value of BufSize is 64 KB, the minimum value is 1 byte. If no value is specified, the default is 128.

To read data from an untyped file:

BlockRead(f, X, Count, QuantBlock);

The procedure reads the number of blocks (per hit) specified by the Count parameter to the variable X. The length of the block corresponds to the length of the buffer. The Count value is never less than 1. The maximum read size is 64 KB per request.

QuantBlock is an optional parameter. It returns the number of blocks read by the current BlockRead operation. If the read operation completes successfully, QuantBlock is Count. In the event of an emergency, QuantBlock will contain the number of blocks that have been successfully read. Thus, the QuantBlock parameter allows you to control the correctness of the read operation.

To write data to an untyped file:

BlockWrite(f, X, Count, QuantBlock);

In one call, the procedure writes from the variable X the number of blocks that were specified by the Count parameter. Block length = buffer length. QuantBlock returns the number of blocks that were successfully written by the current BlockWrite operation.

Attention! You can use the FIlePos, FileSize, and Seek procedures for untyped files, just as you would for typed file procedures.

Example of solving a problem with Pascal files

Task conditions: you need to create a text file in the Pascal language, then through rewriting from it into a second construction file, which begin with a capital or small letter "A" ("a").

In this case, you will need two file variables f1 and f2. Since the files are text, the type of variables is text. The solution of the problem consists of two parts:

  1. Create the first file.
  2. Read the first file and create a second.

It also makes sense to specify another part that was not specified in the task - displaying the contents of the second file on the screen.

Program primer;
Var f1,f2:text;
I,n: integer;
S: string;
Begin
{part 1: form the first file}
Assign(f1, 'file1.txt'); {linking the variable file to a physical file on disk}
Rewrite(f1); {opening the file for writing}
Readln(n) {let's determine the number of lines to be entered}
for i:=1 to n do
begin
readln(s); {enter strings from the keyboard}
writeln(f1,s); {write lines sequentially to the file}
end;
close(f1); {finish working with the first file, now on the disk there is a file named file1.txt containing the lines we entered. At the current stage, the program can finish, you can continue working with the file in another program, at another time, but we will continue}

{Part 2: Reading from the First File and Generating the Second}
Reset(f1); {open the first file for reading}
Assign(f2, ‘file2.txt’); {linking the second file changer to the physical file}
Rewrite(f2); {open a second file to write}

{Then, therefore, read the lines from the first file, verify that the condition is met, and write the necessary lines to the second file. to read from a text file, it is better to use a loop on the condition "until the end of the file"}
While not eof(f1) do
Begin
Readln(f1,s); {from the first file read the next line}
If (s[1]=’A’) or (s[1]=’a’) then
Writeln(f2,s); {in the second file write lines that meet the condition}
End;
Close(f1,f2); {finishing with files}

{3 Third: Display the second file}
Writeln;
Writeln('The second file contains lines:');
Reset(f2); {open a second file to read}
While not eof(f2) do {until the end of the second file}
Begin
Readln(f2,s); {read another line from the second file}
Writeln(s); {display the string on the screen}
End;
End.