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.

Input and output 277<br />

Then the follow<strong>in</strong>g example program writes <strong>in</strong>stance of Person to the file people.txt.<br />

with Text_Io, Pack_Types, Sequential_Io;<br />

use Text_Io, Pack_Types;<br />

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

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

People : Person_Array;<br />

package Io is new Sequential_Io( Person );<br />

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

declare<br />

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

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

People(1) := (Name=>"Mike ", Sex=>Male, Height=>183);<br />

People(2) := (Name=>"Cor<strong>in</strong>na ", Sex=>Female, Height=>171);<br />

People(3) := (Name=>"Miranda ", Sex=>Female, Height=> 74);<br />

Io.Create( File=>Fd, Mode=>Io.Out_File, Name=>File_Name );<br />

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

Io.Write( Fd, People(I) );<br />

end loop;<br />

Io.Close(Fd);<br />

exception<br />

when Name_Error =><br />

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

end;<br />

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

Note:<br />

The package <strong>Ada</strong>.Text_Io is used to provide the def<strong>in</strong>ition of the exception Name_Error.<br />

When us<strong>in</strong>g the generic package <strong>Ada</strong>.Sequential_Io, the procedures read and write are used<br />

to perform the <strong>in</strong>put and output operations.<br />

To read back the data written to the file people.txt the follow<strong>in</strong>g example program is used:<br />

with Text_Io, Pack_Types, Sequential_Io;<br />

use Text_Io, Pack_Types;<br />

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

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

People : Person_Array;<br />

package Io is new Sequential_Io( Person );<br />

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

declare<br />

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

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

Io.Open( File=>Fd, Mode=>Io.In_File, Name=>File_Name );<br />

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

Io.Read( Fd, People(I) );<br />

Put( People(I).Name );<br />

Put( Height_Cm'Image( People(I).Height ) );<br />

if People(I).Sex = Male then<br />

Put(" Male");<br />

else<br />

Put(" Female");<br />

end if;<br />

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

end loop;<br />

Io.Close(Fd);<br />

exception<br />

when Name_Error =><br />

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

end;<br />

end Ma<strong>in</strong>7;<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!