SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
Algorítmica y Programación I

     Archivos : procesamiento
         Archivos en Ada
Procesos
  Apareo de archivos (mezclarlos respetando el orden).

Consiste en intercalar información de dos o más archivos, donde cada uno debe estar
ordenado previamente en el mismo orden y bajo la misma clave.

  ABM de archivos (Altas, Bajas y Modificaciones de información en un archivo).

Los tipos de archivos que estamos estudiando son una fuente de información, y como tal,
necesitamos mantenerla actualizada. La actualización implica agregar, borrar o modificar la
información que se encuentra en un archivo.

  Ordenamiento de un archivo, Búsqueda.

Para ordenar un archivo lo “bajamos” a memoria, a un vector de registros, lo ordenamos
como se ordena un vector de registros, y luego lo “subimos” a disco. Las búsquedas se
pueden realizar sobre el dispositivo, o más rápidamente en la memoria.




                                     Algorítmica y Programación I
Apareo de Archivos
Veremos este modelo de procesamiento al estudiar en la próxima clase
los cortes de control.


           Archivo
           Maestro                                       Archivo de
                                                          Detalles




                                   Impresión 1


                          Algorítmica y Programación I
Archivo1   Archivo2                                  Archivon
                                   …………




             Archivo=Archivo1 U Archivo2 U ……
                         Archivon




                      Algorítmica y Programación I
Clave   Descripcion         SM           SA         PU           Clave   PA
ABM
                         345     zapatos                80            90 122            345     135
                         357     toallas              600           800     32          371      9
                         368     manteles             150            160    63          375     11
                         371     harina             2300            5000        8       380      5
                         375     jabon              2500            2800        9       389     14
                         380     esponja            1200            1300        3       393     17
                         384     lavandina          3000            4500        5       402     36
Mercaderia
                         389     tijeras                50            80    12          407     467
                         393     semillas             120            300    13          427     24
                         398     regador              120            200    10          433     27
                         402     fertilizante         200            356    32
                         407     cubierta             100            134 456
                         413     almohada             200           345     15      Precios_nuevos
SM: stock mínimo
SA : stock actual        427     delantal             250            456    21
PU : Precio unitario
PA: precio actual        433     pañales            2000            5000    23
                                     Algorítmica y Programación I
Clave   Descripcion         SM             SA     PU       Resultado de
ABM                                                                               modificaciones a
                         345   zapatos                80            90 135        Mercadería con
                         357   toallas              600           800     32      Precios_nuevos
                         368   manteles             150            160    63
                         371   harina             2300            5000        9
                         375   jabon              2500            2800    11
                         380   esponja            1200            1300        5
                         384   lavandina          3000            4500        5
Mercaderia
                         389   tijeras                50            80    14
                         393   semillas             120            300    17
                         398   regador              120            200    10
                         402   fertilizante         200            356    36
                         407   cubierta             100            134 467
                         413   almohada             200           345     15
SM: stock mínimo
SA : stock actual        427   delantal             250            456    24
PU : Precio unitario
                         433   pañales            2000            5000    27
                                   Algorítmica y Programación I
Clave   Descripcion          SM            SA     PU    Clave
ABM
                        345    zapatos                80            90 122     357
                        357    toallas              600           800     32   384
                        368    manteles             150            160    63   389
                        371    harina             2300            5000     8   398
                        375    jabon              2500            2800     9   413
                        380    esponja            1200            1300     3
                        384    lavandina          3000            4500    5
Mercaderia
                        389    tijeras                50            80    12
                        393    semillas             120            300    13
                        398    regador              120            200    10
                        402    fertilizante         200            356    32
                        407    cubierta             100            134 456
                        413    almohada             200           345     15   Bajas
SM: stock mínimo
SA : stock actual       427    delantal             250            456    21
PU : Precio unitario
PA: precio actual       433    pañales            2000            5000    23
                                   Algorítmica y Programación I
Clave   Descripcion          SM            SA     PU    Resultado de
ABM                                                                            modificaciones a
                        345    zapatos                80           90 122      Mercadería con
                        368    manteles             150            160    63   bajas de claves
                        371    harina             2300            5000     8
                        375    jabon              2500            2800    9
                        380    esponja            1200            1300     3
                        393    semillas             120           300     13
                        402    fertilizante         200            356    32
Mercaderia
                        407    cubierta             100            134 456
                        427    delantal             250           456     21
                        433    pañales            2000            5000    23




SM: stock mínimo
SA : stock actual
PU : Precio unitario

                                   Algorítmica y Programación I
Clave        Descripcion     SM        SA       PU           Clav Descripci SM       SA     P
ABM                                                                      e    on                        U
            345         zapatos         80          90 122
            368         manteles        150       160        63          348   zapatilla   80     900       11
                                                                                                             3
            371         harina         2300     5000          8
                                                                         370   rejilla     150    800       12
            375         jabon          2500     2800          9
                                                                         382   semola      100    245        7
            380         esponja        1200     1300          3
                                                                         456   maiz        200    450        4
            393         semillas        120       300       13
                                                                         467   arroz       560    899        5
            402         fertilizante    200       356        32
 Mer                                                                     480   fideos      400    800        3
            407         cubierta        100       134 456
 cad
 eria       427         delantal       250        456       21
            433         pañales        2000     5000         23




 SM: stock mínimo
 SA : stock actual                                                          Altas
 PU : Precio unitario

                                          Algorítmica y Programación I
Clave     Descripcion             SM         SA   PU   Resultado de
ABM                    345     zapatos                  80         90 122     modificaciones a
                       348     zapatilla                80         900 113    Mercadería con
                                                                              altas de claves y
                       368     manteles               150          160   63
                                                                              datos
                       370     rejilla                150          800   12
                       371     harina               2300       5000       8
                       375     jabon                2500       2800       9
                       380     esponja              1200       1300       3
                       382     semola                 100          245    7
Mercaderia
                       393     semillas               120          300   13
                       402     fertilizante           200          356   32
                       407     cubierta               100          134 456
                       427     delantal               250          456   21
                       433     pañales              2000       5000      23

SM: stock mínimo
                       456     maiz                   200          450    4
SA : stock actual      467     arroz                  560          899    5
PU : Precio unitario
PA: precio actual      480     fideos                 400          800    3
                                    Algorítmica y Programación I
Archivos en ADA
Nosotros restringiremos nuestro estudio a los archivos secuenciales, de los que a
continuación veremos la sintaxis y requisitos formales para su aplicación:

Los elementos necesarios para manejar archivos secuenciales se encuentran en el
paquete "Sequential_IO".
           with Ada.Sequential_IO;
Declaración
Para poder usar archivos secuenciales se deben definir previamente el tipo de sus
componentes
type TPersona is
record
  Nombre : string(1..20);
  DNI    : string(1..10);
  Edad : natural;
end record;
Una vez definido el tipo, se definen instancias de los paquetes de manejo de
archivos, según el tipo de acceso que se vaya a utilizar.
package ArchTPersona_Sec is new Ada.Sequential_IO(TPersona); - - Acceso
secuencial
 use ArchTPersona_Sec;           Algorítmica y Programación I
Ahora se pueden declarar variables de tipo archivo secuencial:
MiArchivo : ArchTPersona_Sec.tipo_archivo;

Creación de archivo secuencial
Create ( File => <nombre de variable >, Mode => Out_File, -- por defecto
Name => "<nombre de archivo externo>" );
<nombre de variable > -- el nombre de la variable archivo
<external file name> - - el nombre del archivo externo (físico).

  Ejemplo :
  Create ( File => MiArchivo,
              Mode => Out_File,
              Name => "c: MiArchivo.dat" );




                                 Algorítmica y Programación I
Apertura de archivo secuencial
Open ( File => <nombre de variable >, Mode => In_File, Name => "<nombre
de archivo externo>" );
<nombre de variable > - el nombre de la variable archivo
<external file name> - el nombre del archivo externo (físico).

Ejemplo :
Open ( File => MiArchivo,
        Mode => In_File,
        Name => "c: MiArchivo.dat" );
• Mode es el modo de apertura (puede tomar los valores: "In_File",
"Out_File", "Append_File").
• In_File abre el archivo en modo lectura.
• Out_File abre el archivo en modo escritura (si el fichero ya existe,
se vacía).
• Append_File abre un archivo secuencial en modo escritura para
añadir información al final.

                           Algorítmica y Programación I
Cierre de archivo secuencial
Close ( File => < nombre de variable > );
<nombre de variable> - el nombre de la variable archivo.


 Ejemplo :
   Close ( File => MiArchivo);


Operaciones de entrada/salida : Read y Write
Read( File => < nombre de variable >, Item => < nombre componente>);
<nombre de variable> - es el nombre de la variable archivo.
< nombre componente> Nombre del componente del archivo que se lee
desde éste.
Write( File => < nombre de variable >, Item => < nombre componente>);
<nombre de variable> - es el nombre de la variable archivo.
< nombre componente> Nombre del componente del archivo que se graba
en éste.


                              Algorítmica y Programación I
Otras funciones

End_Of_File(Archivo1) es una función que devuelve True si se ha alcanzado el final de
Archivo1 y False en caso contrario.
 Is_Open(Archivo1) devuelve True si el archivo "Archivo1" está abierto y "False" en
caso contrario.
Mode(Archivo1) devuelve el modo en que ha sido abierto el archivo.


Name(Archivo1) devuelve el nombre del archivo externo correspondiente a “Archivo1”
(nombre lógico).
Los errores que pudieran producirse al intentar abrir un archivo pueden controlarse
mediante excepciones.




                                 Algorítmica y Programación I
with ada.Text_Io,ada.Sequential_IO, ada.characters.handling, ada.Integer_Text_IO;
use ada.Text_Io, ada.characters.handling, ada.Integer_Text_IO;
procedure crear_Fichero is
  subtype Cadena20 is String(1..20);
  subtype Cadena8 is String(1..8);
  type T_Persona is
  record
    Nombre: cadena20 ;
    Dni: cadena8;
    Edad: Natural;
  end record;
  package Archi_Persona_Sec is new ada.Sequential_Io(T_Persona);
  use Archi_Persona_Sec;
  F_Entrada: Archi_persona_sec.File_Type;
  Alumno:T_Persona;
  sigue:character;
begin
  --se abren los ficheros
  Create(F_Entrada,Out_File, "F:alumnos.dat");
  loop
  carga_registro(alumno); - - en este procedimiento se genera el registro alumno
  Get_Immediate(Sigue);
  sigue:=to_upper(sigue);
    Write(F_Entrada, Alumno); - - se graba el registro alumnos en el archivo F_Entrada
    exit when sigue/='C';
  end loop;
Close(F_Entrada); --se cierran los ficheros
end crear_Fichero;

                                        Algorítmica y Programación I
with ada.Text_Io,ada.Sequential_IO;
with ada.Text_Io , ada.Integer_Text_IO;
use ada.Text_Io, ada.Integer_Text_IO;
procedure leo_Fichero is
   subtype Cadena20 is String(1..20);
   subtype Cadena8 is String(1..8);
   type T_Persona is
   record
     Nombre: cadena20 ;
     Dni: cadena8;
     Edad: Natural;
   end record;
   package Archi_Persona_Sec is new ada.Sequential_Io(T_Persona);
   use Archi_Persona_Sec;
   F_Entrada: Archi_persona_sec.File_Type;
   Alumno:T_Persona;
  begin
Archi_persona_sec.Open(F_Entrada,In_File, "F:alumnos.dat"); - - se abren los ficheros
 loop exit when Archi_Persona_Sec.End_Of_File(F_Entrada); - - esto equivale a mientras no fin archivo
     archi_persona_sec.Read(F_Entrada, Alumno);
     Put_line("El Nombre y Apellido es ");
     Put_line(alumno.nombre);
     Put_Line("Su DNI");
     put_line(alumno.dni);
     Put_line("Su edad ");
     Put(Alumno.Edad);
     new_line;
     end loop;
archi_persona_sec.Close(F_Entrada); - -se cierran los ficheros
end leo_Fichero;                           Algorítmica y Programación I
-- este programa copia un archivo de texto en otro
with Text_Io;
use Text_Io;
-- El procedimiento Copiar_Fichero copia un fichero de texto
-- llamado "original.txt" en otro llamado "copia.txt"
-- precondiciones: debe existir un fichero externo llamado original.txt
-- no debe existir un fichero externo llamado copia.txt
-- postcondiciones: Existe un fichero externo llamado "copia.txt" cuyo contenido es
-- idéntico al de "original.txt"
procedure Copiar_Fichero_ok is
   F_Entrada, F_Salida: File_Type;
   Línea : String(1..200);
   Lon_Línea : Natural;
begin
   --se abren los ficheros
   Open(F_Entrada,Mode => In_File,Name => "C:original.txt");
   Create(F_Salida,Name => "C:copia.txt");
   --se copia F_Entrada en F_Salida
   while not End_Of_File(F_Entrada) loop
      Get_Line(F_Entrada,Línea,Lon_Línea);
      Put_Line(F_Salida,Línea(1..Lon_Línea));
   end loop;
   --se cierran los ficheros
   Close(F_Entrada);
   Close(F_Salida);
end Copiar_Fichero_ok;                Algorítmica y Programación I
En la próxima clase veremos Cortes de Control ………




                Algorítmica y Programación I

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

ABM Archivos Algorítmica Programación

  • 1. Algorítmica y Programación I Archivos : procesamiento Archivos en Ada
  • 2. Procesos Apareo de archivos (mezclarlos respetando el orden). Consiste en intercalar información de dos o más archivos, donde cada uno debe estar ordenado previamente en el mismo orden y bajo la misma clave. ABM de archivos (Altas, Bajas y Modificaciones de información en un archivo). Los tipos de archivos que estamos estudiando son una fuente de información, y como tal, necesitamos mantenerla actualizada. La actualización implica agregar, borrar o modificar la información que se encuentra en un archivo. Ordenamiento de un archivo, Búsqueda. Para ordenar un archivo lo “bajamos” a memoria, a un vector de registros, lo ordenamos como se ordena un vector de registros, y luego lo “subimos” a disco. Las búsquedas se pueden realizar sobre el dispositivo, o más rápidamente en la memoria. Algorítmica y Programación I
  • 3. Apareo de Archivos Veremos este modelo de procesamiento al estudiar en la próxima clase los cortes de control. Archivo Maestro Archivo de Detalles Impresión 1 Algorítmica y Programación I
  • 4. Archivo1 Archivo2 Archivon ………… Archivo=Archivo1 U Archivo2 U …… Archivon Algorítmica y Programación I
  • 5. Clave Descripcion SM SA PU Clave PA ABM 345 zapatos 80 90 122 345 135 357 toallas 600 800 32 371 9 368 manteles 150 160 63 375 11 371 harina 2300 5000 8 380 5 375 jabon 2500 2800 9 389 14 380 esponja 1200 1300 3 393 17 384 lavandina 3000 4500 5 402 36 Mercaderia 389 tijeras 50 80 12 407 467 393 semillas 120 300 13 427 24 398 regador 120 200 10 433 27 402 fertilizante 200 356 32 407 cubierta 100 134 456 413 almohada 200 345 15 Precios_nuevos SM: stock mínimo SA : stock actual 427 delantal 250 456 21 PU : Precio unitario PA: precio actual 433 pañales 2000 5000 23 Algorítmica y Programación I
  • 6. Clave Descripcion SM SA PU Resultado de ABM modificaciones a 345 zapatos 80 90 135 Mercadería con 357 toallas 600 800 32 Precios_nuevos 368 manteles 150 160 63 371 harina 2300 5000 9 375 jabon 2500 2800 11 380 esponja 1200 1300 5 384 lavandina 3000 4500 5 Mercaderia 389 tijeras 50 80 14 393 semillas 120 300 17 398 regador 120 200 10 402 fertilizante 200 356 36 407 cubierta 100 134 467 413 almohada 200 345 15 SM: stock mínimo SA : stock actual 427 delantal 250 456 24 PU : Precio unitario 433 pañales 2000 5000 27 Algorítmica y Programación I
  • 7. Clave Descripcion SM SA PU Clave ABM 345 zapatos 80 90 122 357 357 toallas 600 800 32 384 368 manteles 150 160 63 389 371 harina 2300 5000 8 398 375 jabon 2500 2800 9 413 380 esponja 1200 1300 3 384 lavandina 3000 4500 5 Mercaderia 389 tijeras 50 80 12 393 semillas 120 300 13 398 regador 120 200 10 402 fertilizante 200 356 32 407 cubierta 100 134 456 413 almohada 200 345 15 Bajas SM: stock mínimo SA : stock actual 427 delantal 250 456 21 PU : Precio unitario PA: precio actual 433 pañales 2000 5000 23 Algorítmica y Programación I
  • 8. Clave Descripcion SM SA PU Resultado de ABM modificaciones a 345 zapatos 80 90 122 Mercadería con 368 manteles 150 160 63 bajas de claves 371 harina 2300 5000 8 375 jabon 2500 2800 9 380 esponja 1200 1300 3 393 semillas 120 300 13 402 fertilizante 200 356 32 Mercaderia 407 cubierta 100 134 456 427 delantal 250 456 21 433 pañales 2000 5000 23 SM: stock mínimo SA : stock actual PU : Precio unitario Algorítmica y Programación I
  • 9. Clave Descripcion SM SA PU Clav Descripci SM SA P ABM e on U 345 zapatos 80 90 122 368 manteles 150 160 63 348 zapatilla 80 900 11 3 371 harina 2300 5000 8 370 rejilla 150 800 12 375 jabon 2500 2800 9 382 semola 100 245 7 380 esponja 1200 1300 3 456 maiz 200 450 4 393 semillas 120 300 13 467 arroz 560 899 5 402 fertilizante 200 356 32 Mer 480 fideos 400 800 3 407 cubierta 100 134 456 cad eria 427 delantal 250 456 21 433 pañales 2000 5000 23 SM: stock mínimo SA : stock actual Altas PU : Precio unitario Algorítmica y Programación I
  • 10. Clave Descripcion SM SA PU Resultado de ABM 345 zapatos 80 90 122 modificaciones a 348 zapatilla 80 900 113 Mercadería con altas de claves y 368 manteles 150 160 63 datos 370 rejilla 150 800 12 371 harina 2300 5000 8 375 jabon 2500 2800 9 380 esponja 1200 1300 3 382 semola 100 245 7 Mercaderia 393 semillas 120 300 13 402 fertilizante 200 356 32 407 cubierta 100 134 456 427 delantal 250 456 21 433 pañales 2000 5000 23 SM: stock mínimo 456 maiz 200 450 4 SA : stock actual 467 arroz 560 899 5 PU : Precio unitario PA: precio actual 480 fideos 400 800 3 Algorítmica y Programación I
  • 12. Nosotros restringiremos nuestro estudio a los archivos secuenciales, de los que a continuación veremos la sintaxis y requisitos formales para su aplicación: Los elementos necesarios para manejar archivos secuenciales se encuentran en el paquete "Sequential_IO". with Ada.Sequential_IO; Declaración Para poder usar archivos secuenciales se deben definir previamente el tipo de sus componentes type TPersona is record Nombre : string(1..20); DNI : string(1..10); Edad : natural; end record; Una vez definido el tipo, se definen instancias de los paquetes de manejo de archivos, según el tipo de acceso que se vaya a utilizar. package ArchTPersona_Sec is new Ada.Sequential_IO(TPersona); - - Acceso secuencial use ArchTPersona_Sec; Algorítmica y Programación I
  • 13. Ahora se pueden declarar variables de tipo archivo secuencial: MiArchivo : ArchTPersona_Sec.tipo_archivo; Creación de archivo secuencial Create ( File => <nombre de variable >, Mode => Out_File, -- por defecto Name => "<nombre de archivo externo>" ); <nombre de variable > -- el nombre de la variable archivo <external file name> - - el nombre del archivo externo (físico). Ejemplo : Create ( File => MiArchivo, Mode => Out_File, Name => "c: MiArchivo.dat" ); Algorítmica y Programación I
  • 14. Apertura de archivo secuencial Open ( File => <nombre de variable >, Mode => In_File, Name => "<nombre de archivo externo>" ); <nombre de variable > - el nombre de la variable archivo <external file name> - el nombre del archivo externo (físico). Ejemplo : Open ( File => MiArchivo, Mode => In_File, Name => "c: MiArchivo.dat" ); • Mode es el modo de apertura (puede tomar los valores: "In_File", "Out_File", "Append_File"). • In_File abre el archivo en modo lectura. • Out_File abre el archivo en modo escritura (si el fichero ya existe, se vacía). • Append_File abre un archivo secuencial en modo escritura para añadir información al final. Algorítmica y Programación I
  • 15. Cierre de archivo secuencial Close ( File => < nombre de variable > ); <nombre de variable> - el nombre de la variable archivo. Ejemplo : Close ( File => MiArchivo); Operaciones de entrada/salida : Read y Write Read( File => < nombre de variable >, Item => < nombre componente>); <nombre de variable> - es el nombre de la variable archivo. < nombre componente> Nombre del componente del archivo que se lee desde éste. Write( File => < nombre de variable >, Item => < nombre componente>); <nombre de variable> - es el nombre de la variable archivo. < nombre componente> Nombre del componente del archivo que se graba en éste. Algorítmica y Programación I
  • 16. Otras funciones End_Of_File(Archivo1) es una función que devuelve True si se ha alcanzado el final de Archivo1 y False en caso contrario. Is_Open(Archivo1) devuelve True si el archivo "Archivo1" está abierto y "False" en caso contrario. Mode(Archivo1) devuelve el modo en que ha sido abierto el archivo. Name(Archivo1) devuelve el nombre del archivo externo correspondiente a “Archivo1” (nombre lógico). Los errores que pudieran producirse al intentar abrir un archivo pueden controlarse mediante excepciones. Algorítmica y Programación I
  • 17. with ada.Text_Io,ada.Sequential_IO, ada.characters.handling, ada.Integer_Text_IO; use ada.Text_Io, ada.characters.handling, ada.Integer_Text_IO; procedure crear_Fichero is subtype Cadena20 is String(1..20); subtype Cadena8 is String(1..8); type T_Persona is record Nombre: cadena20 ; Dni: cadena8; Edad: Natural; end record; package Archi_Persona_Sec is new ada.Sequential_Io(T_Persona); use Archi_Persona_Sec; F_Entrada: Archi_persona_sec.File_Type; Alumno:T_Persona; sigue:character; begin --se abren los ficheros Create(F_Entrada,Out_File, "F:alumnos.dat"); loop carga_registro(alumno); - - en este procedimiento se genera el registro alumno Get_Immediate(Sigue); sigue:=to_upper(sigue); Write(F_Entrada, Alumno); - - se graba el registro alumnos en el archivo F_Entrada exit when sigue/='C'; end loop; Close(F_Entrada); --se cierran los ficheros end crear_Fichero; Algorítmica y Programación I
  • 18. with ada.Text_Io,ada.Sequential_IO; with ada.Text_Io , ada.Integer_Text_IO; use ada.Text_Io, ada.Integer_Text_IO; procedure leo_Fichero is subtype Cadena20 is String(1..20); subtype Cadena8 is String(1..8); type T_Persona is record Nombre: cadena20 ; Dni: cadena8; Edad: Natural; end record; package Archi_Persona_Sec is new ada.Sequential_Io(T_Persona); use Archi_Persona_Sec; F_Entrada: Archi_persona_sec.File_Type; Alumno:T_Persona; begin Archi_persona_sec.Open(F_Entrada,In_File, "F:alumnos.dat"); - - se abren los ficheros loop exit when Archi_Persona_Sec.End_Of_File(F_Entrada); - - esto equivale a mientras no fin archivo archi_persona_sec.Read(F_Entrada, Alumno); Put_line("El Nombre y Apellido es "); Put_line(alumno.nombre); Put_Line("Su DNI"); put_line(alumno.dni); Put_line("Su edad "); Put(Alumno.Edad); new_line; end loop; archi_persona_sec.Close(F_Entrada); - -se cierran los ficheros end leo_Fichero; Algorítmica y Programación I
  • 19. -- este programa copia un archivo de texto en otro with Text_Io; use Text_Io; -- El procedimiento Copiar_Fichero copia un fichero de texto -- llamado "original.txt" en otro llamado "copia.txt" -- precondiciones: debe existir un fichero externo llamado original.txt -- no debe existir un fichero externo llamado copia.txt -- postcondiciones: Existe un fichero externo llamado "copia.txt" cuyo contenido es -- idéntico al de "original.txt" procedure Copiar_Fichero_ok is F_Entrada, F_Salida: File_Type; Línea : String(1..200); Lon_Línea : Natural; begin --se abren los ficheros Open(F_Entrada,Mode => In_File,Name => "C:original.txt"); Create(F_Salida,Name => "C:copia.txt"); --se copia F_Entrada en F_Salida while not End_Of_File(F_Entrada) loop Get_Line(F_Entrada,Línea,Lon_Línea); Put_Line(F_Salida,Línea(1..Lon_Línea)); end loop; --se cierran los ficheros Close(F_Entrada); Close(F_Salida); end Copiar_Fichero_ok; Algorítmica y Programación I
  • 20. En la próxima clase veremos Cortes de Control ……… Algorítmica y Programación I