Sunday, November 1, 2009

10. Files in Pascal ---- Text Files

Sometimes we have to store information externally, say on a hard disk than the computer memory which gets wiped out after the program ends execution. For that purpose Pascal provids some commands.

1. Give names to files and declare them as variables: Var filein, fileout : text;

2. We have to assign these file names to actual physical files on disk and open the files.
assign (filein, 'c:\file1.txt');
rewrite(filein); (* open for writing *)
reset (filein); (* Open file for reading *)
append(filein); (* Open file for adding records to it at the end *)

3. We can use read, readln, write, writeln commands to read and write the files. We have to say which files we are reading and writing.
writeln(filein, is +'AuroraRao');

4. After using the files we have to close them.
close(filein); close(fileout);


5. To make the content different in a record, a string conversion to the record added as the first character of the new record.
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');


6. The following program creates filein with records, reads the created records and copies them to fileout and appends records to filein at the end.



Program Program10;
{Author: Rao S Lakkaraju}
(* Program to demonstrate text Files *)
{**** Text File Handling ****}
uses crt,graph;
var
myrec,is : string;
filein, fileout : text;
indx : integer;

begin
clrscr;
(* creates an input file --- Writes records to an input file *)
(* Reads records from input file *)
(* and writes to an output file *)
writeln('Records in the file');
assign (filein, 'c:\file1.txt');
rewrite(filein);
assign (fileout, 'c:\file2.txt');
rewrite (fileout);

for indx := 1 to 5 do
begin
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');
writeln(filein, is +'Zipcode');
writeln(filein, is +'third record');
end;

close(filein);
reset (filein);


Repeat
readln (filein, myrec);
writeln(myrec);
writeln (fileout, myrec);
until eof(filein);

close(filein);
(* Append records to filein *)
append(filein);
for indx := 6 to 8 do
begin
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');
end;
close(filein);
close(fileout);
readln;
end.

Summary: Pascal can create files on hard disk. For text files we can use read, readln, write, writeln commands for reading and writing. We have to tell which files we are reading and which files we are writing to in the commands.

No comments:

Post a Comment