Вы находитесь на странице: 1из 2

Working with Files in Pascal

Writing to a file:

1. Replace output in the first line of the program with a variable that represents the file you
want to write to.
Program testrite (input, outfile);
2. Declare the variable in the variable as data type text.
var
outfile: text;
3. Assign the path to the variable using the assign statement.
Assign (outfile, ‘H:\sdd\test.txt’);
4. Open the file for writing using the rewrite statement.
Rewrite(outfile);1
5. Use write and writeln statements to write the file, identifying the output location using the
variable name.
Writeln(outfile, ‘This is a test’);
6. Close the file.
Close(outfile);

Sample program:
Program DataSave (input, outfile);

Var
outfile : text;
fname, surname, dob, answer : String;
age : integer;

Begin;
Assign (outfile, ‘H:\SDD\PplData.txt);
Rewrite(outfile);
Repeat
Write(‘Enter your first name: ’);
Readln(fname);
Write(‘Enter your surname: ’);
Readln(surname);
Write(‘Enter your date of birth: ’);
Readln(dob);
Write(‘Enter your age: ’);
Readln(age);
Writeln(outfile, fname, ‘ ‘, surname, ‘ ‘, dob, ‘ ‘, age);
Writeln(‘Do you want to enter more data? y/n’);
Readln(answer);
Until (answer = ‘n’);
Close(outfile);
End.

1
To append data, replace REWRITE with APPEND.
Reading from a file:

1. Replace input in the first line of the program with a variable that represents the file you
want to read from.
Program testread (infile, output);
2. Declare the variable in the variable as data type text.
var
infile: text;
3. Assign the path to the variable using the assign statement.
Assign (infile, ‘H:\SDD\PplData.txt’);
4. Open the file for writing using the reset statement.
Reset(infile);
5. Use read and readln statements to read the file, identifying the input location using the
variable name.
Readln(infile, filedata2);
6. Close the file.
Close(infile);

Sample program:
Program DataPrnt (infile, output);

Var
infile: text;
persdata: String;

Begin;
Assign (infile, ‘H:\SDD\PplData.txt’);
Reset(infile);
While NOT3 EOF4 (infile) do
Begin
Readln(infile, persdata);
Writeln(persdata);
Writeln(‘Press enter to continue’);
Readln;
End;
Close(infile);
End.

Remember: It is important to CLOSE your file at the end of your


program!

2
filedata is a variable to store the data read from the file.
3
NOT is a key word meaning not equal to. It can also be represented by < >
4
EOF is a key word meaning End of File.

Вам также может понравиться