We already have been usingI/O since the first chapter, but only to get going.It is time to dig a little bit deeper, so we can write nicer programs.
In its heydays Pascal was so smart and defined a minimal common, yet convenient interface to interact withI/O.Despite various standardization effortsI/O operations differ among every singleOS, yet – as part of the language – Pascal defines a set of operations to be present, regardless of the utilized compiler orOS.
In thefirst chapter it was already mentioned thatinput andoutput are special program parameters.If you list them in the program parameter list, you can use these identifiers to write and read from the terminal, theCLI you are using.
In fact,input andoutput are variables.Their data type istext.We call a variable that has the data typetext atext file.
The data of atext file are composed oflines.Aline is a (possibly empty) sequence of characters (e. g. letters, digits, spaces or punctuation) until and including a terminating “newline character”.
A file – in general – has the following properties:
All this information isimplicitly available to you, you do not need to take care of it.You can query and alter some information in predefined ways.
All you have to keep in mind in order to successfully use files is that a filehas a mode.The text filesinput andoutput are, once they are listed in the program parameter list, in inspection and generation mode respectively.You canonlyread data from files that are inspection mode.And it is only possible towrite datato files that are generation mode.
Note, due to their special nature the mode ofinput andoutput cannot be changed.
Pascal defines the following routines to read and write to files:
get,put,read/readLn, andwrite/writeLn.The routinesreadLn andwriteLn can only be used in conjunction with text files, whereas all other routines work withany kind of file.In the following sections we will focus onread andwrite.These routines build upon the “low-level”get andput.In thechapter “Files” we will take a look at them, though.
Let’s look at a simple program:
programwriteDemo(output);varx:integer;beginx:=10;writeLn(output,x:20);end.
Copy the program and see what it does.
First, we will learn a new statement, the assignment.Colon equals (:=) is read as “becomes”.In the linex := 10 the variable’s valuebecomes ten.On the left hand side you write a variable name.On the right hand side you put a value.The value has to be valid for the variable’s data type.For instance, you couldnot assign'Hello world!' to the variablex, because it is not a validinteger, i. e. the data typex has.
The power ofwrite/writeLn is that – for text files – it converts the parameters into a human-readable form.On modern computers theinteger valueten is stored in a particularbinary form.00001010 is a visual representation of the bits set (1) and unset (0) for storing “ten”.Yet, despite the binary storage the characters you see on the screen are10.This conversion, from zeroes and ones into a human-readable representation, the character sequence “10”, is doneautomatically.
If the destination ofwrite/writeLn is a text file, all parameters are converted into ahuman-readable form provided such conversion is necessary and makes sense. |
Furthermore, after the parameterx comes :20.As you might have noticed, when you run the program the value ten is printed right-aligned making the 0 in 10 appear at the 20th column (position from the left margin).
The:20 is aformat specifier.It ensures that the given parameter has aminimum width of that many characters and it may fill missing “width” with spaces to left.
Format specifiers in awrite/writeLn call can only be specified where a human-readable representation is necessary, in other words if the destination is a text file. |
Look at this program:
programiceCream(input,output);varresponse:char;beginwriteLn('Do you like ice cream?');writeLn('Type “y” for “yes” (“Yummy!”) and “n” for “no”.');writeLn('Confirm your selection by hitting Enter.');readLn(input,response);ifresponse='y'thenbeginwriteLn('Awesome!');end;end.
All parameters given toread/readLn have to be variables.The first parameter, thesource, has to be a file variable which is currently in inspection mode.We ensure that by puttinginput into the program parameter list.If the source parameter isinput, you are allowed to omit it, thusreadLn(response) is equivalent toreadLn(input, response).
A new language construct which we will cover in detail in the next chapter is theif-then-branch.The code afterthen that is surrounded bybegin andend; is only executed ifresponse equals to the character value 'y'.Otherwise, we are polite and do not express our strong disagreement.
write toinput? Why does / should it work, or not?write toinput. The text fileinput is, provided it is listed in the program parameter list, ininspection mode. That means you can onlyread data from this text file, neverwrite.write toinput. The text fileinput is, provided it is listed in the program parameter list, ininspection mode. That means you can onlyread data from this text file, neverwrite.read to aconstant?read/readLnhave to be variables. A constant, per definition, does not change its value during run-time. That means, also the user cannot assign values to a constant.read/readLnhave to be variables. A constant, per definition, does not change its value during run-time. That means, also the user cannot assign values to a constant.program valentine from the first chapter and improve it with knowledge you have learned in this chapter: Make the heart ideogram appear (sort of) centered. Assume a console window width of 80 characters, or any reasonable width.programvalentine(output);constwidth=49;beginwriteLn(' #### #### ':width);writeLn(' ######## ######## ':width);writeLn('## #### ##':width);writeLn('## # ##':width);writeLn('## ILY ##':width);writeLn(' ## sweetie ## ':width);writeLn(' ### ### ':width);writeLn(' ### ### ':width);writeLn(' ### ### ':width);writeLn(' ### ':width);writeLn(' # ':width);end.
string literal is shorter thanwidth (otherwise it does not resemble a heart ideogram anymore):programvalentine(output);constwidth=49;beginwriteLn('#### #### ':width);writeLn('######## ######## ':width);writeLn('## #### ##':width);writeLn('## # ##':width);writeLn('## ILY ##':width);writeLn('## sweetie ## ':width);writeLn('### ### ':width);writeLn('### ### ':width);writeLn('### ### ':width);writeLn('### ':width);writeLn('# ':width);end.
programvalentine(output);constwidth=49;beginwriteLn(' #### #### ':width);writeLn(' ######## ######## ':width);writeLn('## #### ##':width);writeLn('## # ##':width);writeLn('## ILY ##':width);writeLn(' ## sweetie ## ':width);writeLn(' ### ### ':width);writeLn(' ### ### ':width);writeLn(' ### ### ':width);writeLn(' ### ':width);writeLn(' # ':width);end.
string literal is shorter thanwidth (otherwise it does not resemble a heart ideogram anymore):programvalentine(output);constwidth=49;beginwriteLn('#### #### ':width);writeLn('######## ######## ':width);writeLn('## #### ##':width);writeLn('## # ##':width);writeLn('## ILY ##':width);writeLn('## sweetie ## ':width);writeLn('### ### ':width);writeLn('### ### ':width);writeLn('### ### ':width);writeLn('### ':width);writeLn('# ':width);end.
o--------------------------------------o| || || || |o--------------------------------------o
''. It is two straight typewriter’s apostrophes back-to-back. You can use it in your solution.''. It is two straight typewriter’s apostrophes back-to-back. You can use it in your solution.programbox(output);constspace=38;beginwriteLn('o--------------------------------------o');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('o--------------------------------------o');end.
'':space will generate 38 (that is the value of the constantspace) spaces. If you are really smart, you have noticed that the top and bottom edges of the box are thesame literal twice. We can shorten our program even further:programbox(output);constspace=38;topAndBottomEdge='o--------------------------------------o';beginwriteLn(topAndBottomEdge);writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn(topAndBottomEdge);end.
programbox(output);constspace=38;beginwriteLn('o--------------------------------------o');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('o--------------------------------------o');end.
'':space will generate 38 (that is the value of the constantspace) spaces. If you are really smart, you have noticed that the top and bottom edges of the box are thesame literal twice. We can shorten our program even further:programbox(output);constspace=38;topAndBottomEdge='o--------------------------------------o';beginwriteLn(topAndBottomEdge);writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn(topAndBottomEdge);end.
Notes: