COMPUTACION 2009 Clase 13.

1 COMPUTACION Clase 13 ...
Author: Trinidad Maestre Salazar
0 downloads 2 Views

1 COMPUTACION Clase 13

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

3 Persistencia de los datosPersistencia 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

4 Persistencia de los datosLa 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ó. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

5 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 que 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 !). 4/15/2017 Computación - Fac. Ingeniería - UNMDP

6 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

7 Archivos con tipo: característicasEl 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

8 Archivos con tipo: ejemploSecuencia de componentes del mismo tipo(números enteros) 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

9 Computación - Fac. Ingeniería - UNMDPAcceso 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

10 Computación - Fac. Ingeniería - UNMDPSintaxis 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 4/15/2017 Computación - Fac. Ingeniería - UNMDP

11 Computación - Fac. Ingeniería - UNMDPEjemplo: Type arch_ent= file of integer; Var f:arch_ent; Puntero del archivo Marca de fin de archivo 2223 4453 eof -987 6667 2345 1 -9876 f Componentes 4/15/2017 Computación - Fac. Ingeniería - UNMDP

12 Computación - Fac. Ingeniería - UNMDPArchivos: 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) Reset(f) Rewrite(f) Read(f,x) Write(f,x) Filesize(f) Seek(f,pos) Close(f) Filepos(f) 4/15/2017 Computación - Fac. Ingeniería - UNMDP

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

14 Computación - Fac. Ingeniería - UNMDPCreació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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

15 Lectura de un archivo existenteReset(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). 4/15/2017 Computación - Fac. Ingeniería - UNMDP

16 Otras operaciones con archivosFilesize(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 4/15/2017 Computación - Fac. Ingeniería - UNMDP

17 Otras operaciones con archivosClose(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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

18 Computación - Fac. Ingeniería - UNMDPEjemplo 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

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

20 Computación - Fac. Ingeniería - UNMDPEjemplo 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

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

22 Computación - Fac. Ingeniería - UNMDPEjemplo 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

23 Computación - Fac. Ingeniería - UNMDPprogram archi3; var nume:file of integer; x:integer; begin assign(nume,'c:\tp\artp\primero.dat'); rewrite(nume); write('ingrese un numero: '); readln(x); while x<>0 do write(nume,x); end; close(nume); end. Escribe registros (enteros) mientras el entero sea distinto de cero. Siempre agrega al final. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

24 Computación - Fac. Ingeniería - UNMDPEjemplo 4: lectura de un archivo con un número arbitrario de componentes Mostrar el contenido del archivo creado en el ejemplo3. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

25 Computación - Fac. Ingeniería - UNMDPprogram archi4; var nume:file of integer; i,x:integer; begin assign(nume,'c:\tp\artp\primero.dat'); reset(nume); writeln('los numeros del archivo son: '); while not EOF(nume) do read(nume,x); writeln(x); end; close(nume); end. Esta función es verdadera cuando se encuentra el fin de archivo 4/15/2017 Computación - Fac. Ingeniería - UNMDP

26 Computación - Fac. Ingeniería - UNMDPEjemplo 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

27 Computación - Fac. Ingeniería - UNMDPprogram archi5; var nume:file of integer; i,x:integer; begin assign(nume,'c:\tp\artp\primero.dat'); reset(nume); writeln('el numero en el registro nro 2 es:'); seek(nume,2); read(nume,x); writeln(x); writeln('ingrese la posicion del nro que desea ver: '); readln(i); seek(nume,i); close(nume); end. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

28 Computación - Fac. Ingeniería - UNMDPEjemplo 6: actualización de un archivo Agregar un nuevo registro al archivo creado en el ejemplo 3 4/15/2017 Computación - Fac. Ingeniería - UNMDP

29 Computación - Fac. Ingeniería - UNMDPprogram archi6; var nume:file of integer; x:integer; begin assign(nume,'c:\tp\artp\primero.dat'); reset(nume); seek(nume,filesize(nume)); write('ingrese un numero: '); readln(x); write(nume,x); close(nume); end. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

30 Computación - Fac. Ingeniería - UNMDPEjercicio 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: cantidad total de pasajeros 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

31 Computación - Fac. Ingeniería - UNMDPprogram 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; 4/15/2017 Computación - Fac. Ingeniería - UNMDP

32 Computación - Fac. Ingeniería - UNMDPprocedure crearArchi(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 writeln('Ingrese datos del turista numero ',i,' =========='); with tur do 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); 4/15/2017 Computación - Fac. Ingeniería - UNMDP

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

34 Computación - Fac. Ingeniería - UNMDPprocedure 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; noesta:=true; 4/15/2017 Computación - Fac. Ingeniería - UNMDP

35 Computación - Fac. Ingeniería - UNMDPwhile (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; 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; 4/15/2017 Computación - Fac. Ingeniería - UNMDP

36 Computación - Fac. Ingeniería - UNMDPprocedure 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; 4/15/2017 Computación - Fac. Ingeniería - UNMDP

37 Computación - Fac. Ingeniería - UNMDPBEGIN {programa principal} clrscr; assign(todos,'tourist10.dat'); crearArchi(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 4/15/2017 Computación - Fac. Ingeniería - UNMDP

38 Computación - Fac. Ingeniería - UNMDPRun-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 FileMode value. 15 Invalid drive number The number given to the Getdir or ChDir 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,FilePos, FileSize, Flush, BlockRead, and BlockWrite if the file is not open. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

39 Computación - Fac. Ingeniería - UNMDPRun-time errors 104 File not open for input Reported by Read, BlockRead, Eof, Eoln, SeekEof or SeekEoln 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, GetMem or ReallocMem, 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. 4/15/2017 Computación - Fac. Ingeniería - UNMDP

40 Computación - Fac. Ingeniería - UNMDPRun-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 AssertErrorProc procedural variable was installed. 4/15/2017 Computación - Fac. Ingeniería - UNMDP