18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

186 Child libraries<br />

13.4 The cat program revisited<br />

The program to concatenate the contents of files previously seen <strong>in</strong> Section 3.11 can now be re-written to give a<br />

sensible error message to the user when an attempt is made to list a file that does not exist. In this program the<br />

follow<strong>in</strong>g exception occur:<br />

Exception<br />

Name_Error<br />

Status_Error<br />

Explanation<br />

File does not exist.<br />

File is already open.<br />

This new program is:<br />

with <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Command_L<strong>in</strong>e;<br />

use <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Command_L<strong>in</strong>e;<br />

procedure Cat is<br />

Fd : <strong>Ada</strong>.Text_Io.File_Type; --File descriptor<br />

Ch : Character;<br />

--Current character<br />

beg<strong>in</strong><br />

if Argument_Count >= 1 then<br />

for I <strong>in</strong> 1 .. Argument_Count loop --Repeat for each file<br />

beg<strong>in</strong><br />

Open( File=>Fd, Mode=>In_File, --Open file<br />

Name=>Argument(I) );<br />

while not End_Of_File(Fd) loop --For each L<strong>in</strong>e<br />

while not End_Of_L<strong>in</strong>e(Fd) loop--For each character<br />

Get(Fd,Ch); Put(Ch); --Read / Write character<br />

end loop;<br />

Skip_L<strong>in</strong>e(Fd); New_L<strong>in</strong>e; --Next l<strong>in</strong>e / new l<strong>in</strong>e<br />

end loop;<br />

Close(Fd);<br />

--Close file<br />

exception<br />

when Name_Error =><br />

Put("cat: " & Argument(I) & " no such file" );<br />

New_L<strong>in</strong>e;<br />

when Status_Error =><br />

Put("cat: " & Argument(I) & " all ready open" );<br />

New_L<strong>in</strong>e;<br />

end;<br />

end loop;<br />

else<br />

Put("Usage: cat file1 ... "); New_L<strong>in</strong>e;<br />

end if;<br />

end Cat;<br />

13.5 A stack<br />

A stack is a structure used to store and retrieve data items. Data items are pushed onto the structure and retrieved<br />

<strong>in</strong> reverse order. This is commonly referred to as ‘first <strong>in</strong> last out’. This process is illustrated <strong>in</strong> Figure 13.1<br />

Stack<br />

2<br />

1 1 1<br />

After send<strong>in</strong>g<br />

message<br />

Push(1) Push(2) Pop() Pop()<br />

2 1<br />

Figure 13.1 Example of operations on a stack.<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!