Ada语言文件操作之直接IO(Direct_IO)

85 阅读2分钟

直接IO (Direct_IO

 

接IO在机器层面上涉及一种称为存储器直接访问Direct Memory Access,简称DMA)的硬件,它可以对存储器直接进行访问,这样可以解放CPU,它们可以协同工作,表现出很高的效率,这明显区别于顺序IO—依赖于CPU的。我们来通过例程来看看直接IO的能力。直接IO具有大块内容的快速读写能力,这点看起来用于游戏资源的加载更有优势。直接模式的文件模式和顺序IO的文件模式稍有区别,有:In_File、Inout_File、Out_File,就是只读文件、读写文件、只写文件。

面是直接IO的例程:

with Ada.Direct_IO;


procedure Direct_IO_Test is


subtype String12 is String(1..12);


package String12_IO is new Ada.Direct_IO (Element_Type => String12);

use String12_IO;


File : File_Type;


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


data:constant String := "Ada Lovelace,the world first programmer!   ";


dataLen:constant Integer := data'Length;


dataRem:Integer:= dataLen rem String12'Length;


-- 判断文件是否存在

function IsFileExist(fn:String) return Boolean is

use String12_IO;

dFile:File_Type;

begin

Open(dFile,In_File,fn);

if Is_Open(dFile) then

Close(dFile);

end if;

return True;

exception when others =>

return False;

end IsFileExist;


begin


if not IsFileExist(fn) then


Create(File,out_File,fn);


else


Open(File,out_File,fn);


end if;


declare


n : Integer := 0;


begin


for i in 1..dataLen/12 loop


Write(File,data(n12 + data'First .. n12 + data'First+11));


n := n+1;


end loop;


end;


if dataRem /= 0 then


declare


S12 : String12 := (others => ASCII.NUL);


n : Integer := 1;


begin


for i in data'Last-dataRem+1 .. data'Last loop


S12(n):=data(i);


n:=n+1;


end loop;


Write(File,S12);


end;


end if;



Reset(File,Inout_File);


Set_Index(File,Size(File));


Write(File,"Love is all.");


if Is_Open(File) then


Close(File);


end if;


end Direct_IO_Test;

在直接IO包Ada.Direct_IO中,相对于顺序IO,多了两种功能:获取文件尺寸与文件定位功能。但从前面的例程中我们可以看到仍然有不足的地方:为了凑定义类型的尺寸不得不专门写了一个程序块来写入剩余的内容。接下来,我们将介绍的流IO就比较完善了,这个问题将不复存在。