如何在ADA编程中不覆盖输入/输出中的数据

  • 本文关键字:输出 数据 ADA 编程 覆盖 ada
  • 更新时间 :
  • 英文 :


我需要从用户那里获取输入并将数据保存在文件中,但数据不得被覆盖。代码运行良好,但数据被覆盖。如何更正我的代码以获得所需的结果?

我无法设法覆盖数据。需求是:"要求用户逐个输入名称、id和CGPA,然后将其写入文件中。现有数据不得为".我也尝试将新生成的文件数据存储在另一个文件中,但得到相同的结果。

with Ada.Command_Line, Ada.Text_IO;
use Ada.Command_Line, Ada.Text_IO;
procedure Main is
-- Initializing
Read_From     : constant String := "inputFile.txt";
Write_To      : constant String := "studentData.txt";
name          : String (1 .. 13);
studentID     : String (1 .. 11);
cgpa          : String (1 .. 4);
Input, Output : File_Type;
begin
-- taking inputs
Put_Line ("My Student ID Is *******bc150400162*******");
Put_Line ("Enter the details for first student.");
Put_Line ("Please enter your name:");
Get (name);
Put_Line ("Please enter your Student ID:");
Get (studentID);
Put_Line ("Please enter your CGPA:");
Get (cgpa);
-- opening file
begin
Open (File => Input, Mode => In_File, Name => Read_From);
exception
when others =>
Put_Line
(Standard_Error,
"Can not open the file '" & Read_From & "'. Does it exist?");
Set_Exit_Status (Failure);
return;
end;
-- Creating new file file
begin
Create (File => Output, Mode => Out_File, Name => Write_To);
exception
when others =>
Put_Line
(Standard_Error, "Can not create a file named '" & Write_To & "'.");
Set_Exit_Status (Failure);
return;
end;
-- Here is the loop.............................................
------------------
loop
declare
Line : String := Get_Line (Input);
begin
Put_Line (Output, Line);
Put_Line (Output, "The Student details are: ");
Put_Line (Output, name);
Put_Line (Output, studentID);
Put_Line (Output, cgpa);
end;
end loop;
exception
when End_Error =>
if Is_Open (Input) then
Close (Input);
end if;
if Is_Open (Output) then
Close (Output);
end if;
end Main;

执行此操作的标准方法是尝试在追加模式下打开文件,如果失败,请创建它(再次,在追加模式下)。如果创建文件失败,您会遇到其他问题(例如,名称非法?没有权限?文件系统是只读的?文件系统已满?这些在您的程序中都无法寻址!)

注意,先打开,如果打开失败,则创建;反之,文件可能会重置,这正是您不想要的。

with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.IO_Exceptions;
procedure Appending is
Output : Ada.Text_IO.File_Type;
Name : constant String := "appending.dat";
begin

我们在这里需要一个块,所以可以在这里捕获异常。

begin

尝试打开文件...

Ada.Text_IO.Open (File => Output,
Name => Name,
Mode => Ada.Text_IO.Append_File);

Open成功了!

exception
when Ada.IO_Exceptions.Name_Error =>

Open失败,因为名称不代表可打开的文件。尝试创建它...

Ada.Text_IO.Create (File => Output,
Name => Name,
Mode => Ada.Text_IO.Append_File);

文件Output现在处于追加模式。
(乍一看,您可能想知道在追加模式下打开必须为空的文件的意义何在。当然,通常情况下,它也可能在标准输出模式下打开;唯一的区别是,如果由于某种原因您必须使用无模式Reset。在这种情况下,如果文件是在追加模式下创建的,它将保持追加模式,因此以前的任何更新都不会丢失。

end;

写一些"独特"的东西,这样我们就可以说它有效了......

Ada.Text_IO.Put_Line
(File => Output,
Item => Ada.Calendar.Formatting.Image (Ada.Calendar.Clock));

。我们完成了。可能会让操作系统在退出时为我们关闭文件,但让我们确定一下。

Ada.Text_IO.Close (File => Output);
end Appending;

最新更新