0% found this document useful (0 votes)
16 views47 pages

Week11 2+12

The document discusses programming with text files in Pascal, including defining text files and file variables, opening and preparing files for reading and writing, reading and writing data from text files, checking for end of line and end of file, and closing files after processing. It provides examples of declaring, opening, reading from and writing to text files as well as functions for testing end of line and end of file conditions.

Uploaded by

manar mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views47 pages

Week11 2+12

The document discusses programming with text files in Pascal, including defining text files and file variables, opening and preparing files for reading and writing, reading and writing data from text files, checking for end of line and end of file, and closing files after processing. It provides examples of declaring, opening, reading from and writing to text files as well as functions for testing end of line and end of file conditions.

Uploaded by

manar mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

CMP 131

Introduction to Computer
Programming
Violetta Cavalli-Sforza
Week 11, Lecture 2 (Wed)
THIS WEEK
• Today
– Programming with text files
– Quiz results & going over ..
• Thursday: LAB 01
– More work on homework #5
NEXT WEEK
• Quiz #4
– Wednesday May 30th
• No make-up session
• I don’t feel a need for more class time
but… I can possibly start classes 15
minutes early and end 15 minutes late
(since you have ½ hour breaks).
– Let me know if you want me to do that!
Topics
• Definitions
• Advantages of data files
• Text file operations
– Declare
– Initialize
– Use
– Close
• <eof> & <eoln> characters
• eof & eoln functions
• Reading/Writing characters
• Reading/Writing numeric data
Definitions
• Interactive program:
– Reads all input data from the keyboard and displays
output on the screen (terminal I/O)
• Batch processing:
– Input and output are from data files
• Pure batch processing:
– Input and output are strictly from data files, no
interaction with user
• Examples are the pipe and filter processing in Unix, Linux and
MSDOS
• Mixed interactive and batch processing:
– Have both terminal I/O and file I/O
Definitions [cont.]
• Data file (input file):
– A general definition
– A file containing input data for a program
– In Pascal, it could be a binary file (not readable by a
human) or a text file.
• Output file:
– A file containing program results
• Text file:
– A disk file containing a collection of characters
– Text files can be viewed or created using a text editor
– Can be used for input or output
Advantages of Using Data Files
• Entering data interactively
– Is ok, if you only have a few data items
– If you have lots of data, you want to do it ONCE and
then store the data
– It is easy to make errors
• If you do, it’s hard to fix them
• You need to start all over again … lots of extra work
• Entering data with a data file
– We can run the program as many times a you wish
without reentering the data.
• If program output is written to a file, a permanent
copy will be available.
• The output file generated by one program can
be used as input data to another file.
Advantages of Using Text Files
• Created with a text editor or similar tool
that can write text files
• Easy to check & edit.
• You can establish your own format, e.g.
– Have several fields per line
– Fields are separated by tab characters,
blanks, comma, or other special character
A File, Conceptually Is

dataitem separator dataitem … dataitem separator dataitem <eoln>


dataitem separator dataitem … dataitem separator dataitem <eoln>
dataitem separator dataitem … dataitem separator dataitem <eoln>

dataitem separator dataitem … dataitem separator dataitem <eoln>
dataitem separator dataitem … dataitem separator dataitem <eoln>
<eof>
Text Files In General
• A collection of characters stored under some name in
secondary memory.
• Consist of multiple lines of character type
• Each character occupies one byte, including the <eoln>
& <eof>
• Have no fixed size
• <eof> marks an end-of-file
• The last <eoln> character is followed by the <eof>
character in the file
• Both the keyboard & screen are considered as text files
• Some systems represent the <eof> on the keyboard by
ctrl/Z
Special File Characters
• <eoln>
– Indicates the end-of-line
– Inserted each time the keyboard's Enter key is
pressed
– Similar to end-of-line in terminal input stream
• <eof>
– Indicates the end-of-file
– Inserted automatically after the last character of a text
file when the file is saved
– Ctrl-D (Unix and related) or Ctrl-Z (MS DOS) are
equivalents for terminal streams
Reading Text Files
• readln:
– Read data and skip the rest of input line and go to the
start of the next data line.
– Any additional characters remaining on the current data
line are not processed.
– Example: If the file contains on each line:
number1 number2 number3 … numberN <eoln>
and you read with the statement:
readln(Value1, Value2);
number3 … numberN will be thrown away
• read:
– Read data from the same data line during successive
calls.
– When you get to the end of the line, use readln without
arguments to go to the next line
Writing Text Files
• Use writeln, and write
• These work like when you are writing to
standard output
• You can use formatting directives
Reading a Line of Characters
• Input data will be stored in the variables
specified in the input list.
• The order of the data must correspond to the
order of the variables in the input list.
• One or more blank character must be inserted
between numeric data.
• No blanks required between character data
items.
• readln without an input list will skip over any
characters on the current data line.
• All of this is the same as reading from the
keyboard (input)
Testing for End-of-Line
• eoln function
– Pascal defined function (standard function)
– Returns true when the next data character is the <eoln>
symbol; otherwise false
– Usually used as a sentinel
– Form:
eoln(filename)
Input is a filename
Output is a boolean
– If filename is omitted, keyboard is assumed (input)
Processing A Text File Line
• Example: Counting nonblank characters in a line

{Process each input character up to eoln}


Count := 0; Safer to use WHILE than REPEAT
WHILE NOT eoln(infile) DO
BEGIN
read ( infile, Next ); {Get next character.}
IF Next <> Blank THEN
Count := Count + 1;
END;
readln(infile); {Skip the <eoln>.}

• The last readln statement skips the <eoln>, not the


character at the start of the next data line.
• An attempt to read beyond the <eof> character results in
run-time error.
Testing for End-of-File
• eof function
– Pascal defined function (standard function)
– Returns true if the next character is the <eof>
character
– Form:
eof(filename)
Input is a filename
Output is a boolean
– If filename is omitted, screen is assumed
(input)
Using Text Files
• To use Text files in your program, you
must:
1. Create a text file variable
2. Associate the variable with a physical disk file
3. Open the file for reading or writing
4. Read and write to the file
5. Close the file
Declaring Text Files
• Pascal's predefined data type text is used
to declare text files.
• Syntax:
VAR file-name : text;
• Example:
VAR InData,OutData :
text;
Text File Variables, Logical Files,
and Physical Files
• It is possible to read data from more than one input file
or to write result to more than one output file in a single
program.
• A file variable represents a logical file
• A logical file is explicitly associated with a physical file by
stating the drive, the path, and the physical file name
(next slide)
• The same file variable (logical file) can be associated
with different physical files in the same program but not
at the same time.
– If you have to keep accessing several different input and/or
output files at the same time, use different file variables
Opening/Preparing Input Files:
assign, reset
• First, associate a file variable (logical file) with a physical file:

assign(input file logical name, physical file name);

• Then, prepare the file for reading:

reset ( input file logical name );

• Example:

VAR InFile: text;

assign(InFile, 'InData.Dat' );
reset (InFile);
Opening/Preparing Input Files
[cont.]
• reset:
– Moves the file position pointer to the beginning of the file
– The file position pointer points to the file buffer and selects the
next character to be processed in the file
– Must be done before any characters are read from the input file
– An error is generated if the input file was not previously saved on
disk

dataitem dataitem … dataitem <eoln>


dataitem dataitem … dataitem <eoln>
file
position dataitem dataitem … dataitem <eoln>
pointer …
<eof>
Opening/Preparing Output Files:
assign, rewrite
• First, associate a file variable (logical file) with a physical file:

assign(output file logical name, physical file name);

• Then, prepare the file for writing:

rewrite (output file logical name );

• Example:

VAR OutFile: text;

assign(OutFile, ‘OutData.dat' );
rewrite (OutFile);
Opening/Preparing Output Files
[cont.]
• rewrite:
– Prepares the file for output
– If the file doesn’t exist, an empty file is created
– If the file exists, file position pointer is put to the
beginning of the file.
– All old data are lost!

file
position
pointer
Closing Input & Output Files
• When you are done processing the file, close it:
close (input/output logical file name)
• Example:
VAR MyFile: text;

assign(MyFile, ‘MyData.txt' );
… {process data/file}
close(MyFile);
• Closing essentially makes sure the entire file is
saved correctly.
Self-Check 1
• What is wrong with this program?

assign(‘MyData.txt’, InFile);
rewrite(Infile); /* ?? */
reset(Infile);
WHILE NOT eoln DO /* ?? */
BEGIN
read(InFile, Next);
write(Next)
END; {while}
Example: Copying a file
PROGRAM CopyFile; {Copies InData file to OutData file}
VAR InData, {input file}
OutData : text; {output file}
PROCEDURE CopyLine (VAR InData, OutData : text);
{Copies a line of file InData to file OutData.
BEGIN . . . END { see next slide }

BEGIN {CopyFile}
assign (InData, ‘C:\TP\TEST\InFile.dat’);
assign (OutData, ‘C:\TP\TEST\OutFile.dat’);
reset (InData);
rewrite (OutData);
WHILE NOT eof(InData) DO
CopyLine (InData, OutData);
writeln (OutPut, 'Input file copied to output file.');
close (InData);
close (OutData)
end. {CopyFile}
Example: Copying a file [cont.]
PROCEDURE CopyLine (VAR InData, OutData : text);
{Copies a line of file InData to file OutData.}
VAR Ch : char;

BEGIN

WHILE NOT eoln(InData) DO


BEGIN
read(InData,Ch);
write(OutData,Ch);
END;
readln(InData);
writeln(OutData);

END; {CopyLine}
Example: Copying a file
[alternative]
BEGIN {CopyFile}

assign (InData, ‘C:\TP\TEST\InFile.dat’);


assign (OutData, ‘C:\TP\TEST\OutFile.dat’);
reset (InData);
rewrite (OutData);
WHILE NOT eof(InData) DO
BEGIN Need to add
WHILE NOT eoln(InData) DO Ch: char;
BEGIN to VAR declarations
read(InData,Ch);
write(OutData,Ch);
END;
readln(InData);
writeln(OutData);
END;
writeln (OutPut, 'Input file copied to output file.');
close (InData);
close (OutData)
END. {CopyFile}
Reading/Writing Numeric Data
• When reading numeric data, the computer skips
over any leading blanks or <eoln> character.
until it encounters a sign or digit
• If several variables are listed in the parameter
list for Read or ReadLn, the computer reads
data into each variable in the order in which the
variables appear
• The file position pointer advances after each
value is entered
• Writing a numeric value to a file is similar to
writing to the screen
Reading/Writing Numeric Data
• Example: If the following variables are declared:

X : real; N : Integer; C: Char;


• For the sequence:
1234.56 789 A345.67<eoln>
W<eoln><eof>
Variables values
Statement X N C
1.Read (InData, X, N, C) 1234.56 789 ‘ ‘
2.Read (InData, X, N, C, C) 1234.56 789 ‘A’
3.ReadLn (InData, X, N, C) 1234.56 789 ‘ ‘
4.Read (InData, X, C, N) 1234.56 789 ‘ ‘
5.ReadLn (InData, X, C, N) 1234.56 789 ‘ ‘
6.Read (InData, C, X, N) 234.56 789 ‘1‘
7.ReadLn (InData, C, X, N) 234.56 789 ‘1‘
8.ReadLn(InData,X,N); Read(InData,C) 1234.56 789 ‘W‘
9.ReadLn (InData,X) ReadLn(InData,C) 1234.56 --- ‘W‘
Reading/Writing with Text Files
• Syntax:
read (infile, input-list)
readln (infile, input-list)
write (outfile, output-list)
writeLn (outfile, output-list)
• If infile or outfile are omitted, the standard
default input (keyboard) or output (Screen)
will be assumed
Recursion
Looping/Iteration vs. Recursion
• Looping/iteration is repetition of the same piece
of code with slightly different values of
– the index variable (for FOR loops)
– the control variable/expression (for WHILE and
REPEAT loops)
• With each repetition, the index variable
approaches the maximum (FOR .-. TO…) or
minimum limit (FOR … DOWNTO …)
• During some repetition, the control variable will
cause the loop entrance condition to become
false (WHILE loop) or true (REPEAT loop).
Iteration vs. Recursion
• Recursion is an alternative to iteration
• The idea is to
– Do a little bit of work towards a problem so
that you can then
– Perform a similar operation on a “smaller”
version of the same problem
• Requires the use of procedures or
functions
• A recursive function / procedure calls itself
Conceptual Example
• You have a list of ordered (sorted)
numbers:
1 3 7 15 22 23 28 30 31 45 60 71 72 83 90
• You want to know whether it contains a
specific number: 45
• You can search through the list starting at
the beginning or at the end
• You can “bisect” the list recursively
1. Look at the middle number:
1 3 7 15 22 23 28 30 31 45 60 71 72 83 90
45 > 30, so look above 30:
2. Look at the middle number:
31 45 60 71 72 83 90
45 < 71 so look below 71:
3. Look at the middle number:
31 45 60
Success!
(If you had wanted 47, you would have continued
looking at 60 and decided that it wasn’t there).

NOTE: Each time we are looking at a smaller set


of numbers!!!
Example: Exponentiation
• Exponentiation = powers of a number
• There is no standard Pascal function for it
• So we make one: Power
– A program with iteration
– A function with iteration
– A function with recursion
A Program that Computes Powers
PROGRAM Power;
VAR Num, NumExp: real;
I, Pow :integer;
BEGIN
write('Enter Number (real) and Power (integer): ');
readln(Num,Pow);
NumExp := 1;
FOR I := 1 TO Pow DO
NumExp := NumExp * Num;
writeln(Num:5:2, ' raised to the power ', Pow,
' is ', NumExp:10:2);
readln
END.
An Iterative Function that
Computes Powers
FUNCTION Exponentiate
(Num : real; Pow : integer) : real;
VAR NumExp: real;
I : integer;
BEGIN
NumExp := 1;
FOR I := 1 TO Pow DO
NumExp := NumExp * Num;
Exponentiate := NumExp
END; {Exponentiate}
How the Function is Used
PROGRAM Power;
VAR TheNumber, NumToPower: real;
ThePower :integer;

FUNCTION Exponentiate (Num : real; Pow : integer) : real;



END; {Exponentiate}
BEGIN
write('Enter Number (real) and Power (integer): ');
readln(TheNumber, ThePower);
NumToPower := Exponentiate(TheNumber, ThePower);
writeln(TheNumber:5:2, ' raised to the power ', ThePower,
' is ', NumToPower:10:2);
readln

END.
A Recursive Function that
Computes Powers
FUNCTION Exponentiate
(Num : real; Pow : integer) : real;
BEGIN
IF Pow = 0 THEN
Exponentiate := 1
ELSE
Exponentiate := Num *
Exponentiate(Num, Pow -1)
END; {Exponentiate}
A Recursive Function that
Computes Powers
FUNCTION Exponentiate
(Num : real; Pow : integer) : real;
BEGIN
IF Pow = 0 THEN
Exponentiate := 1
ELSE
Exponentiate := Num *
Exponentiate(Num, Pow -1)
END; {Exponentiate}
How Does it Work?
FUNCTION Exponentiate
(Num : real; Pow : integer) : real;
VAR Result : real;
BEGIN
IF Pow = 0 THEN
Result := 1
ELSE
Result := Num * Exponentiate(Num, Pow -1)
writeln('Num is ', Num:5:2, ' Pow is ', Pow:5,
' Result is ', Result:10:2);
Exponentiate := Result;
END; {Exponentiate}
Enter Number (real) and Power (integer): 3.00 4
Num is 3.00, Pow is 0, Result is 1.00
Num is 3.00, Pow is 1, Result is 3.00
Num is 3.00, Pow is 2, Result is 9.00
Num is 3.00, Pow is 3, Result is 27.00
Num is 3.00, Pow is 4, Result is 81.00
Why Recursion?
• Some problems lend themselves recursion
• Mathematically very elegant
• Computationally:
– More expensive
– But can be efficient in special cases
THE END!

You might also like