Ada语言文件操作之顺序IO(sequential_io)

95 阅读1分钟

顺序IO (sequential_IO


    顺序IO,顾名思义,它是一种一步一步操作的IO,不能回头的。顺序IO有三种文件方式:In_FileOut_FileAppend_File,这三种模式意思是只读文件只写文件附加文件

只写文件与附加文件都是只写的,这两种模式下,是不能进行读取操作的。只写文件一旦设置,文件内容会被清空;附加文件一旦设置,则会定位到文件内容的末尾,对文件进行内容附加;只读文件一旦设置,是不能对文件进行写入的。以下是一段顺序IO的例程。

with Ada.Text_IO;

with Ada.Sequential_IO;


procedure Sequential_IO_Test is


package Char_IO is new Ada.Sequential_IO (Element_Type => Character);

use Char_IO;


File : File_Type;


fn : constant String := "sequential_io_test.txt";


data:constant String := "Ada Lovelace";


data2:constant String := " –the world first programmer!";


Buffer:String(1..100):=(others => Ascii.Nul);


-- 判断文件是否存在

function IsFileExist(fn:String) return Boolean is

sFile:Char_IO.File_Type;

begin

Char_IO.Open(sFile,Char_IO.In_File,fn);

if Char_IO.Is_Open(sFile) then

Char_IO.Close(sFile);

end if;

return True;

exception when others =>

return False;

end;


begin


if not IsFileExist(fn) then

Create(File,Out_File,fn);

else

Open(File,Out_File,fn);

end if;


for i in data'range loop

Write(File,data(i));

end loop;


Reset(File,In_File);

for i in data'range loop

Read(File,Buffer(i));

end loop;


Reset(File,Append_File);


for i in data2'range loop

Write(File,data2(i));

end loop;


if Is_Open(File) then

Close(File);

end if;


end Sequential_IO_Test;