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.

276 Input and output<br />

The follow<strong>in</strong>g program appends <strong>in</strong>stances of Number, one of the <strong>in</strong>teger types to the end of the file<br />

file.txt:<br />

with Text_Io;<br />

use Text_Io;<br />

procedure Ma<strong>in</strong> is<br />

type Number is range 1 .. 10;<br />

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

File_Name: constant Str<strong>in</strong>g:= "file.txt";--Name<br />

package Pack_Number_Io is new Text_Io.Integer_Io( Number );<br />

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

Open( File=>Fd, Mode=>Append_File, Name=>File_Name );<br />

for I <strong>in</strong> Number loop<br />

Pack_Number_Io.Put( Fd, I ); New_L<strong>in</strong>e( Fd );<br />

end loop;<br />

Close(Fd);<br />

exception<br />

when Name_Error =><br />

Put("Cannot append to " & File_Name ); New_L<strong>in</strong>e;<br />

end Ma<strong>in</strong>;<br />

18.3 Read<strong>in</strong>g and writ<strong>in</strong>g b<strong>in</strong>ary data<br />

Any <strong>in</strong>stance of a type may be read and written to a file us<strong>in</strong>g the package <strong>Ada</strong>.Sequential_io. By us<strong>in</strong>g this<br />

package, b<strong>in</strong>ary images of objects may be read and written. For example, the follow<strong>in</strong>g code writes <strong>in</strong>stances of<br />

the data structure Person to the file people.txt. Firstly the Package_Types def<strong>in</strong>es the data structure<br />

Person used to represent an <strong>in</strong>dividual person.<br />

package Pack_Types is<br />

Max_Chs : constant := 10;<br />

type Gender is ( Female, Male );<br />

type Height_Cm is range 0 .. 300;<br />

type Person is record<br />

Name : Str<strong>in</strong>g( 1 .. Max_Chs ); --Name as a Str<strong>in</strong>g<br />

Height : Height_Cm := 0; --Height <strong>in</strong> cm.<br />

Sex : Gender; --Gender of person<br />

end record;<br />

type Person_Index is range 1 .. 3;<br />

subtype Person_Range is Person_Index;<br />

type Person_Array is array ( Person_Range ) of Person;<br />

end Pack_Types;<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!