COMPUTACION 2009 Clase 13 Tipos de Datos PASCAL

  • Slides: 40
Download presentation
COMPUTACION 2009 Clase 13

COMPUTACION 2009 Clase 13

Tipos de Datos PASCAL Estructurados Estáticos Simples Registros Archivos Arreglos Primitivos Vectores No primitivos

Tipos de Datos PASCAL Estructurados Estáticos Simples Registros Archivos Arreglos Primitivos Vectores No primitivos Matrices String N-dimensionales Boolean Real 6/7/2021 Char Integer Computación - Fac. Ingeniería UNMDP 2

Persistencia de los datos n n Persistencia es la característica que le permite a

Persistencia de los datos n n Persistencia es la característica que le permite a la información existir mas allá del tiempo de vida del programa que lo instancia. La persistencia permite al programador almacenar, transferir y recuperar información. Una forma de lograrlo es a través de los archivos de datos. 6/7/2021 Computación - Fac. Ingeniería UNMDP 3

Persistencia de los datos n Ø Ø La información puede ser: Transitoria: cuyo tiempo

Persistencia de los datos n Ø Ø La información puede ser: Transitoria: cuyo tiempo de vida depende directamente del ámbito donde fue instanciada. Persistente: es almacenada en un medio secundario para su posterior reconstrucción y utilización, por lo que su tiempo de vida es independiente del programa que la instanció. 6/7/2021 Computación - Fac. Ingeniería UNMDP 4

Estructura de datos: archivos (file) ØUd. ya conoce el uso de archivos. Ha trabajado

Estructura de datos: archivos (file) ØUd. ya conoce el uso de archivos. Ha trabajado con archivos. pas , archivos. exe, y archivos. txt ØAhora veremos archivos que contengan los datos queremos preservar. Pascal contiene una estructura de datos específica para tratar el problema de la manipulación de datos en almacenamientos externos, como los discos rígidos. ØLa estructura se llama FILE (o archivo !). 6/7/2021 Computación - Fac. Ingeniería UNMDP 5

Estructura de datos: archivos (file) ØTurbo Pascal soporta tres tipos básicos de archivos: <

Estructura de datos: archivos (file) ØTurbo Pascal soporta tres tipos básicos de archivos: < Archivos con tipo < Archivos de texto (ya visto) < Archivos sin tipo (no se verán) ØTodos tienen características comunes: se usan para entrada, para salida o para ambos. La entrada se produce cuando un programa toma datos de un archivo y los usa en el programa; la salida guarda los resultados de un programa en un archivo (o a una impresora, por ejemplo). Igualmente un archivo puede servir para entrada y salida. 6/7/2021 Computación - Fac. Ingeniería UNMDP 6

Archivos con tipo: características ØEl almacenamiento de los datos, en los archivos con tipo,

Archivos con tipo: características ØEl almacenamiento de los datos, en los archivos con tipo, mantiene el formato del almacenamiento en la memoria RAM. ØEsto significa que no hay procesos de traducción, se copia directamente de memoria a disco y viceversa. Ø La razón por la cual almacenamos datos en un archivo es, básicamente, para guardarlos, actualizarlos y mostrarlos. ØGeneralmente guardamos grupos de datos. En los archivos con tipo, cada uno de los datos tiene un tipo específico (como real, string, etc. ) formando una secuencia con cada uno de ellos. 6/7/2021 Computación - Fac. Ingeniería UNMDP 7

Archivos con tipo: ejemplo ØSecuencia de componentes del mismo tipo(números enteros) 2345 -9876 1

Archivos con tipo: ejemplo ØSecuencia de componentes del mismo tipo(números enteros) 2345 -9876 1 2345 6667 -987 4453 2222 eof ØVemos que la estructura dada es la secuencia y esta, en particular, es conocida como archivo secuencial. ØPascal usa la palabra file para designar una estructura consistente en una secuencia de componentes, todas del mismo tipo. 6/7/2021 Computación - Fac. Ingeniería UNMDP 8

Acceso a las componentes ØMediante la secuencia, se define un ordenamiento natural de sus

Acceso a las componentes ØMediante la secuencia, se define un ordenamiento natural de sus componentes y en cualquier instante solo uno de ellos es accesible directamente. ØLos restantes componentes se acceden recorriendo secuencialmente el archivo. ØCada vez que se agregan componentes, se hace al final. 6/7/2021 Computación - Fac. Ingeniería UNMDP 9

Sintaxis de la declaración de archivos Type Identificador = FILE OF Tipo de componente

Sintaxis de la declaración de archivos Type Identificador = FILE OF Tipo de componente (o tipo base); Tipo de los componentes (también se los denomina registros, eventualmente pueden presentar una estructura record). Puede ser cualquier tipo, excepto otro tipo file 6/7/2021 Computación - Fac. Ingeniería UNMDP 10

Ejemplo: Type Puntero del archivo arch_ent= file of integer; Var Marca de fin de

Ejemplo: Type Puntero del archivo arch_ent= file of integer; Var Marca de fin de archivo f: arch_ent; 2345 -9876 1 2345 6667 -987 0 2 3 4 5 1 f 4453 6 2223 eof 7 Componentes 6/7/2021 Computación - Fac. Ingeniería UNMDP 11

Archivos: ØLos operadores básicos para manejo de archivos son los siguientes procedimientos y funciones

Archivos: ØLos operadores básicos para manejo de archivos son los siguientes procedimientos y funciones (f es una variable de tipo file): Assign(f, 'b: archivo. dat) Rewrite(f) Write(f, x) Seek(f, pos) Filepos(f) 6/7/2021 Reset(f) Read(f, x) Filesize(f) Close(f) Computación - Fac. Ingeniería UNMDP 12

Enlace de un archivo lógico con un archivo físico Assign(f, ‘c: archivo. dat'); procedimiento

Enlace de un archivo lógico con un archivo físico Assign(f, ‘c: archivo. dat'); procedimiento que crea un enlace entre el archivo lógico (f) con un archivo físico externo en disco. 6/7/2021 Computación - Fac. Ingeniería UNMDP 13

Creación de un archivo Rewrite(f); procedimiento que precede a la reescritura del archivo f.

Creación de un archivo Rewrite(f); procedimiento que precede a la reescritura del archivo f. Sea cual fuere el valor de f , es reemplazado por el archivo vacío. Eof(f) se vuelve true y se puede grabar un nuevo archivo. Write(f, x); procedimiento que permite grabar una componente x del archivo desde la memoria a un archivo f en disco. 6/7/2021 Computación - Fac. Ingeniería UNMDP 14

Lectura de un archivo existente Reset(f); procedimiento que reposiciona la ventana del archivo(el puntero

Lectura de un archivo existente Reset(f); procedimiento que reposiciona la ventana del archivo(el puntero f ) al principio de este para su lectura, es decir, asigna a f el valor del primer elemento de f. eof(f) resulta false si f no está vacío y true cuando lo está. Read(f, x); procedimiento que permite leer desde un archivo f, una de sus componentes y almacenarla en x (en memoria). 6/7/2021 Computación - Fac. Ingeniería UNMDP 15

Otras operaciones con archivos Filesize(f) función que devuelve la cantidad de componentes que posee

Otras operaciones con archivos Filesize(f) función que devuelve la cantidad de componentes que posee el archivo. Filepos(f) función que devuelve la posición del componente donde se encuentra el control 6/7/2021 Computación - Fac. Ingeniería UNMDP 16

Otras operaciones con archivos Close(f) procedimiento que cierra el archivo, vacía el buffer y

Otras operaciones con archivos Close(f) procedimiento que cierra el archivo, vacía el buffer y lo almacena, libera al gestor de archivo del DOS y actualiza directorio. Cierra un archivo que fue previamente abierto con REWRITE, RESET o APPEND. Seek(f, pos) procedimiento que permite ubicar a f al comienzo de la posición pos. 6/7/2021 Computación - Fac. Ingeniería UNMDP 17

Ejemplo 1: Creación de un archivo ØLa creación de un archivo consiste el almacenar

Ejemplo 1: Creación de un archivo ØLa creación de un archivo consiste el almacenar datos en una estructura de archivo ØA continuación veremos un programa sencillo para crear un archivo de números enteros. 6/7/2021 Computación - Fac. Ingeniería UNMDP 18

program archiv 1; type archi=file of integer; var a: archi; Enlace con un archivo

program archiv 1; type archi=file of integer; var a: archi; Enlace con un archivo externo b, c, i, n: integer; begin Deja el archivo listo para almacenar assign(a, 'datos. dat'); nuevos datos rewrite(a); writeln('ingrese la cantidad de elementos'); readln(n); for i: =1 to n do begin write('Ingrese un dato: '); readln(c); Almacena una componente del write(a, c); archivo end; Se cierra el archivo Computación - Fac. Ingeniería close(a); end. 6/7/2021 UNMDP 19

Ejemplo 2: Lectura secuencial de un archivo ya creado • Luego de crear un

Ejemplo 2: Lectura secuencial de un archivo ya creado • Luego de crear un archivo, esos datos almacenados generalmente en un disco, pueden ser usados para diversos usos. • La primer acción es acceder a todos los datos a través de una lectura, en forma secuencial. 6/7/2021 Computación - Fac. Ingeniería UNMDP 20

program archiv 2; type archi=file of integer; var a: archi; b, c, i, n:

program archiv 2; type archi=file of integer; var a: archi; b, c, i, n: integer; El puntero se coloca al principio del archivo para comenzar la begin lectura si este no está vacío. assign(a, 'datos. dat'); reset(a); writeln('ingrese la cantidad de elementos'); readln(n); for i: =1 to n do SE lee una componente del archivo. begin read(a, c); writeln('el numero es: ', c); end; close(a); end. Computación - Fac. Ingeniería 6/7/2021 UNMDP 21

Ejemplo 3: creación de un archivo con un número arbitrario de componentes Ø Almacenaremos

Ejemplo 3: creación de un archivo con un número arbitrario de componentes Ø Almacenaremos en un archivo una cantidad desconocida de números enteros distintos de cero. 6/7/2021 Computación - Fac. Ingeniería UNMDP 22

program archi 3; var nume: file of integer; x: integer; begin assign(nume, 'c: tpartpprimero.

program archi 3; var nume: file of integer; x: integer; begin assign(nume, 'c: tpartpprimero. dat'); rewrite(nume); write('ingrese un numero: '); Escribe registros (enteros) readln(x); mientras el entero sea while x<>0 do distinto de cero. Siempre begin agrega al final. write(nume, x); write('ingrese un numero: '); readln(x); end; close(nume); Computación - Fac. Ingeniería end. 6/7/2021 UNMDP 23

Ejemplo 4: lectura de un archivo con un número arbitrario de componentes • Mostrar

Ejemplo 4: lectura de un archivo con un número arbitrario de componentes • Mostrar el contenido del archivo creado en el ejemplo 3. 6/7/2021 Computación - Fac. Ingeniería UNMDP 24

program archi 4; var nume: file of integer; i, x: integer; begin assign(nume, 'c:

program archi 4; var nume: file of integer; i, x: integer; begin assign(nume, 'c: tpartpprimero. dat'); reset(nume); writeln('los numeros del archivo son: '); while not EOF(nume) do begin read(nume, x); Esta función es verdadera writeln(x); cuando se encuentra el fin end; de archivo close(nume); end. 6/7/2021 Computación - Fac. Ingeniería UNMDP 25

Ejemplo 5: acceso aleatorio + Veremos el acceso aleatorio: podemos acceder a algunas de

Ejemplo 5: acceso aleatorio + Veremos el acceso aleatorio: podemos acceder a algunas de las componente del archivo moviendo el puntero con la función seek. . +Tomando el archivo generado en el Ej. 3, mostrar el contenido de: a) componente número 2 (es la tercera componente !) b) componente i-ésima ingresando i por teclado. 6/7/2021 Computación - Fac. Ingeniería UNMDP 26

program archi 5; var nume: file of integer; i, x: integer; begin assign(nume, 'c:

program archi 5; var nume: file of integer; i, x: integer; begin assign(nume, 'c: tpartpprimero. dat'); reset(nume); writeln('el numero en el registro nro 2 es: '); seek(nume, 2); read(nume, x); writeln('ingrese la posicion del nro que desea ver: '); readln(i); seek(nume, i); read(nume, x); writeln(x); close(nume); Computación - Fac. Ingeniería end. 6/7/2021 UNMDP 27

Ejemplo 6: actualización de un archivo Ø Agregar un nuevo registro al archivo creado

Ejemplo 6: actualización de un archivo Ø Agregar un nuevo registro al archivo creado en el ejemplo 3 6/7/2021 Computación - Fac. Ingeniería UNMDP 28

program archi 6; var nume: file of integer; x: integer; begin assign(nume, 'c: tpartpprimero.

program archi 6; var nume: file of integer; x: integer; begin assign(nume, 'c: tpartpprimero. dat'); reset(nume); seek(nume, filesize(nume)); write('ingrese un numero: '); readln(x); write(nume, x); close(nume); end. 6/7/2021 Computación - Fac. Ingeniería UNMDP 29

Ejercicio La secretaría de Turismo posee los datos del movimiento de personas a distintos

Ejercicio La secretaría de Turismo posee los datos del movimiento de personas a distintos puntos del país realizado el feriado largo de Semana Santa. Esos datos fueron obtenidos en terminales de omnibus y aeropuertos. Se conoce: 1) cantidad total de pasajeros 2) Por pasajero: medio de transporte ( ómnibus o avión) , ciudad de origen, ciudad de destino. Se desea saber, usando archivos: a) Determinar cuáles fueron las tres ciudades más visitadas al terminar Semana Santa. b) Calcular el porcentaje de turistas que utilizaron el avión y el porcentaje que usó el ómnibus para llegar a dichas ciudades. c) Imprimir la lista de las ciudades origen de los turistas a la ciudad más visitada: imprimir la lista de ciudades origen sin repetirlas junto con la cantidad de turistas que salió a la ciudad mas visitada. 6/7/2021 Computación - Fac. Ingeniería UNMDP 30

program archis; uses crt; type turista=record transpor: 1. . 2; {1 - avion ;

program archis; uses crt; type turista=record transpor: 1. . 2; {1 - avion ; 2: omnibus} ciudadorigen: string[15]; ciudaddestino: string[15]; end; grupoturistas= file of turista; tres=array[1. . 10] of string[15]; vector=array[1. . 40] of integer; Var todos: grupoturistas; cantidad: integer; tresciud: tres; i, k: integer; tur: turista; porbus, poravion: real; 6/7/2021 Computación - Fac. Ingeniería UNMDP 31

procedure crear. Archi(var todos: grupoturistas; var cantidad: integer); var i: integer; tur: turista; begin

procedure crear. Archi(var todos: grupoturistas; var cantidad: integer); var i: integer; tur: turista; begin write('Ingrese la cantidad total de turistas : '); readln(cantidad); rewrite(todos); for i: =1 to cantidad do begin writeln('Ingrese datos del turista numero ', i, ' ====='); with tur do begin write('Medio de transporte que uso 1: avion ; 2: omnibus '); readln(transpor); write('Ciudad de origen : '); readln(ciudadorigen); write('Ciudad destino : '); readln(ciudaddestino); end; write(todos, tur); end; 6/7/2021 Computación - Fac. Ingeniería UNMDP 32

procedure insercion( var cont: vector; var ci: tres; n: integer); var i, j, aux

procedure insercion( var cont: vector; var ci: tres; n: integer); var i, j, aux 1: integer; aux 2: STRING[15]; begin FOR i: =2 TO n DO begin aux 1: =cont[i]; {la clave es cont} aux 2: =ci[i]; j: =i; WHILE (j>1) and (cont[j-1]<aux 1) DO begin cont[j]: =cont[j-1]; ci[j]: =ci[j-1]; j: =j-1 end; cont[j]: =aux 1; ci[j]: =aux 2; end; 6/7/2021 Computación - Fac. Ingeniería UNMDP 33

procedure tresmasvisitadas(var todos: grupoturistas; var tresciud: tres; var ww: integer); var i, w, tot,

procedure tresmasvisitadas(var todos: grupoturistas; var tresciud: tres; var ww: integer); var i, w, tot, k: integer; tur: turista; ci: tres; cont: vector; noesta: boolean; BEGIN reset(todos); read(todos, tur); ci[1]: =tur. ciudaddestino; cont[1]: =1; Tot: =1; for i: =2 to filesize(todos) do begin k: =1; read(todos, tur); noesta: =true; 6/7/2021 Computación - Fac. Ingeniería UNMDP 34

while (k<= Tot) and (noesta) do if tur. ciudaddestino=ci[k] then begin cont[k]: =cont[k]+1; noesta:

while (k<= Tot) and (noesta) do if tur. ciudaddestino=ci[k] then begin cont[k]: =cont[k]+1; noesta: =false; end else k: =k+1; if noesta then begin tot: =tot+1; ci[tot]: =tur. ciudaddestino; cont[tot]: =1 end; {for} insercion(cont, ci, tot); if tot < 3 then ww: =tot else ww: =3; for i: =1 to ww do tresciud[i]: =ci[i]; END; 6/7/2021 Computación - Fac. Ingeniería UNMDP 35

procedure porcent(cantidad: integer; var todos: grupoturistas; tresciud: tres; var porbus, poravion: real); var avion,

procedure porcent(cantidad: integer; var todos: grupoturistas; tresciud: tres; var porbus, poravion: real); var avion, i, bus: integer; Begin reset(todos); avion: =0; bus: =0; for i: =1 to filesize(todos) do begin read(todos, tur); IF (tur. ciudaddestino=tresciud[1]) or (tur. ciudaddestino=tresciud[2]) or (tur. ciudaddestino=tresciud[3]) then if tur. transpor=1 then avion: =avion+1 else bus: =bus+1; end; porbus: =(100*bus)/cantidad; poravion: =(100*avion)/cantidad; end; 6/7/2021 Computación - Fac. Ingeniería UNMDP 36

BEGIN {programa principal} clrscr; assign(todos, 'tourist 10. dat'); crear. Archi(todos, cantidad); tresmasvisitadas(todos, tresciud, k);

BEGIN {programa principal} clrscr; assign(todos, 'tourist 10. dat'); crear. Archi(todos, cantidad); tresmasvisitadas(todos, tresciud, k); writeln('Ciudades mas visitadas ========'); for i: =1 to k do writeln(tresciud[i]); porcent(cantidad, todos, tresciud, porbus, poravion); writeln('Porcentajes por omnibus: ', porbus: 5: 2, ' por avion: ', poravion: 5: 2); close(todos); readln END. Falta completar el inciso c 6/7/2021 Computación - Fac. Ingeniería UNMDP 37

Run-time errors Applications generated by Free Pascal might generate Run-time error when certain abnormal

Run-time errors Applications generated by Free Pascal might generate Run-time error when certain abnormal conditions are detected in the application. This appendix lists the possible run-time errors and gives information on why they might be produced. 1 Invalid function number An invalid operating system call was attempted. 2 File not found Reported when trying to erase, rename or open a non-existent file. 3 Path not found Reported by the directory handling routines when a path does not exist or is invalid. Also reported when trying to access a non-existent file. 4 Too many open files The maximum number of currently opened files by your process has been reached. Certain operating systems limit the number of files which can be opened concurrently, and this error can occur when this limit has been reached. 5 File access denied Permission accessing the file is denied. This error might be caused by several reasons: • Trying to open for writing a file which is read only, or which is actually a directory. • File is currently locked or used by another process. • Trying to create a new file, or directory while a file or directory of the same name already exists. • Trying to read from a file which was opened in write only mode. • Trying to write from a file which was opened in read only mode. • Trying to remove a directory or file while it is not possible. • No permission to access the file or directory. 6 Invalid file handle If this happens, the file variable you are using is trashed; it indicates that your memory is corrupted. 12 Invalid file access code Reported when a reset or rewrite is called with an invalid File. Mode value. 15 Invalid drive number The number given to the Getdir or Ch. Dir function specifies a nonexistent disk. 16 Cannot remove current directory Reported when trying to remove the currently active directory. 17 Cannot rename across drives You cannot rename a file such that it would end up on another disk or partition. 100 Disk read error An error occurred when reading from disk. Typically when you try to read past the end of a file. 101 Disk write error Reported when the disk is full, and you’re trying to write to it. 102 File not assigned This is reported by Reset, Rewrite, Append, Rename and Erase, if you call them with an unassigned file as a parameter. 103 File not open Reported by the following functions : Close, Read, Write, Seek, Eof, File. Pos, File. Size, Flush, Block. Read, and Block. Write if the file is not open. 6/7/2021 Computación - Fac. Ingeniería UNMDP 38

Run-time errors 104 File not open for input Reported by Read, Block. Read, Eof,

Run-time errors 104 File not open for input Reported by Read, Block. Read, Eof, Eoln, Seek. Eof or Seek. Eoln if the file is not opened with Reset. 105 File not open for output Reported by write if a text file isn’t opened with Rewrite. 106 Invalid numeric format Reported when a non-numeric value is read from a text file, when a numeric value was expected. 150 Disk is write-protected (Critical error) 151 Bad drive request struct length (Critical error) 152 Drive not ready (Critical error) 154 CRC error in data (Critical error) 156 Disk seek error (Critical error) 157 Unknown media type (Critical error) 158 Sector Not Found (Critical error) 159 Printer out of paper (Critical error) 160 Device write fault (Critical error) 161 Device read fault (Critical error) 162 Hardware failure (Critical error) 200 Division by zero The application attempted to divide a number by zero. 201 Range check error If you compiled your program with range checking on, then you can get this error in the following cases: 1. An array was accessed with an index outside its declared range. 2. Trying to assign a value to a variable outside its range (for instance an enumerated type). 202 Stack overflow error The stack has grown beyond its maximum size (in which case the size of local variables should be reduced to avoid this error), or the stack has become corrupt. This error is only reported when stack checking is enabled. 203 Heap overflow error The heap has grown beyond its boundaries. This is caused when trying to allocate memory exlicitly with New, Get. Mem or Realloc. Mem, or when a class or object instance is created and no memory is left. Please note that, by default, Free Pascal provides a growing heap, i. e. the heap will try to allocate more memory if needed. However, if the heap has reached the maximum size allowed by the operating system or hardware, then you will get this error. 204 Invalid pointer operation This you will get if you call Dispose or Freemem with an invalid pointer (notably, Nil) 205 Floating point overflow You are trying to use or produce too large real numbers. 206 Floating point underflow You are trying to use or produce too small real numbers. 207 Invalid floating point operation Can occur if you try to calculate the square root or logarithm of a negative number. 210 Object not initialized When compiled with range checking on, a program will report this error if you call a virtual method without having called istr constructor. 6/7/2021 Computación - Fac. Ingeniería UNMDP 39

Run-time errors 211 Call to abstract method Your program tried to execute an abstract

Run-time errors 211 Call to abstract method Your program tried to execute an abstract virtual method. Abstract methods should be overridden, and the overriding method should be called. 212 Stream registration error This occurs when an invalid type is registered in the objects unit. 213 Collection index out of range You are trying to access a collection item with an invalid index (objects unit). 214 Collection overflow error The collection has reached its maximal size, and you are trying to add another element (objects unit). 215 Arithmetic overflow error This error is reported when the result of an arithmetic operation is outside of its supported range. Contrary to Turbo Pascal, this error is only reported for 32 -bit or 64 -bit arithmetic overflows. This is due to the fact that everything is converted to 32 -bit or 64 -bit before doing the actual arithmetic operation. 216 General Protection fault The application tried to access invalid memory space. This can be caused by several problems: 1. Deferencing a nil pointer 2. Trying to access memory which is out of bounds (for example, calling move with an invalid length). 217 Unhandled exception occurred An exception occurred, and there was no exception handler present. The sysutils unit installs a default exception handler which catches all excpetions and exits gracefully. 219 Invalid typecast Thrown when an invalid typecast is attempted on a class using the as operator. This error is also thrown when an object or class is typecast to an invalid class or object and a virtual method of that class or object is called. This last error is only detected if the –CR compiler option is used. 223 Threads not supported Thread management relies on a separate driver on some operating systems (notably, unixes). The unit with this driver needs to be specified on the uses clause of the program, preferably as the first unit. (cthreads on unix) 227 Assertion failed error An assertion failed, and no Assert. Error. Proc procedural variable was installed. 6/7/2021 Computación - Fac. Ingeniería UNMDP 40