40
Clase 13 COMPUTACION 2009

Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

Embed Size (px)

Citation preview

Page 1: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

Clase 13

COMPUTACION 2009

Page 2: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 2

Tipos de Datos PASCAL Tipos de Datos PASCAL EstructuradosEstructurados

SimplesSimples

PrimitivosPrimitivos

No primitivosNo primitivos

EstáticosEstáticos

IntegerIntegerRealReal CharCharBooleanBooleanStringString

Archivos

RegistrosRegistros

ArreglosArreglos

VectoresVectores

MatricesMatrices

N-dimensionalesN-dimensionales

Page 3: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 3

Persistencia de los datos

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.

Page 4: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 4

Persistencia de los datos

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ó.

Page 5: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 5

Estructura de datos: archivos Estructura de datos: archivos (file)(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 !).

Page 6: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 6

Estructura de datos: archivos Estructura de datos: archivos (file)(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.

Page 7: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 7

Archivos con tipo: Archivos con tipo: característicascaracterí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.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.

Page 8: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 8

Archivos con tipo: ejemploArchivos con tipo: ejemplo

2345 -9876 1 2345 6667 -987 4453 2222 eof2345 -9876 1 2345 6667 -987 4453 2222 eof

Secuencia de componentes del mismo tipo(números enteros)

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.

Page 9: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 9

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.

Acceso a las Acceso a las componentescomponentes

Page 10: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 10

Type Identificador = FILE OF Tipo de componente (o tipo base);

Sintaxis de la declaración de Sintaxis de la declaración de archivosarchivos

Tipo de los componentes (también se los denomina registros, eventualmente pueden presentar una estructura record). Puede ser cualquier tipo, excepto otro tipo file

Page 11: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 11

22234453 eof-987666723451-9876

2345

f

0 1 2 3 4 5 6 7

ComponentesComponentes

Type arch_ent= file of integer;Var f:arch_ent;

Ejemplo:Ejemplo:

Marca de fin de archivo

Puntero del archivo

Page 12: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 12

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)

Archivos: Archivos:

Page 13: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 13

Enlace de un archivo lógico con Enlace de un archivo lógico con un archivo físicoun archivo físico

procedimiento que crea un enlace entre el archivo lógico (f) con un archivo físico externo en disco.

Assign(f,‘c:\archivo.dat');

Page 14: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 14

Creación de un archivoCreación de un archivo

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.

Rewrite(f);

Write(f,x);

procedimiento que permite grabar una componente x del archivo desde la memoria a un archivo f en disco.

Page 15: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 15

Lectura de un archivo existenteLectura de un archivo existente

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á.

Reset(f);

procedimiento que permite leer desde un archivo f, una de sus componentes y almacenarla en x (en memoria).

Read(f,x);

Page 16: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 16

Otras operaciones con archivosOtras operaciones con archivos

función que devuelve la cantidad de componentes que posee el archivo.

Filesize(f)

función que devuelve la posición del componente donde se encuentra el control

Filepos(f)

Page 17: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 17

Otras operaciones con archivos Otras operaciones con archivos

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.

Close(f)

Seek(f,pos) procedimiento que permite ubicar a f al comienzo de la

posición pos.

Page 18: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 18

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.

Ejemplo 1: Creación de un archivoEjemplo 1: Creación de un archivo

Page 19: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 19

program 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 begin write('Ingrese un dato:'); readln(c); write(a,c); end;close(a); end.

Enlace con un archivo externoEnlace con un archivo externo

Deja el archivo listo para almacenar nuevos datos

Deja el archivo listo para almacenar nuevos datos

Almacena una componente del archivo

Almacena una componente del archivo

Se cierra el archivoSe cierra el archivo

Page 20: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 20

• 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.

Ejemplo 2: Lectura secuencial de un Ejemplo 2: Lectura secuencial de un archivo ya creadoarchivo ya creado

Page 21: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 21

program 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 begin 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.

El puntero se coloca al principio del archivo para comenzar la lectura si este no está vacío.

SE lee una componente del archivo.

SE lee una componente del archivo.

Page 22: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 22

Almacenaremos en un archivo una cantidad desconocida de números enteros distintos de cero.

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

Page 23: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 23

program 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 begin write(nume,x); write('ingrese un numero: '); readln(x); end; close(nume); end.

Escribe registros (enteros) mientras el entero sea distinto de cero. Siempre agrega al final.

Page 24: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 24

• Mostrar el contenido del archivo creado en el ejemplo3.

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

Page 25: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 25

program 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 begin read(nume,x); writeln(x); end; close(nume); end.

Esta función es verdadera cuando se encuentra el fin de archivo

Esta función es verdadera cuando se encuentra el fin de archivo

Page 26: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 26

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.

Ejemplo 5: acceso aleatorio Ejemplo 5: acceso aleatorio

Page 27: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 27

program 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); read(nume,x); writeln(x); close(nume); end.

Page 28: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 28

Agregar un nuevo registro al archivo creado en el ejemplo 3

Ejemplo 6: actualización de un archivoEjemplo 6: actualización de un archivo

Page 29: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 29

program 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.

Page 30: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

EjercicioLa 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.

04/21/23Computación - Fac. Ingeniería

- UNMDP 30

Page 31: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 31

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;

Vartodos:grupoturistas;cantidad:integer;tresciud:tres;i,k:integer;tur:turista;porbus,poravion:real;

Page 32: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 32

procedure crearArchi(var todos:grupoturistas;var cantidad:integer);vari: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; end;

Page 33: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 33

procedure insercion( var cont:vector;var ci:tres; n:integer); var i,j,aux1:integer; aux2:STRING[15]; begin

FOR i:=2 TO n DO begin aux1:=cont[i];{la clave es cont} aux2:=ci[i]; j:=i; WHILE (j>1) and (cont[j-1]<aux1) DO begin cont[j]:=cont[j-1]; ci[j]:=ci[j-1]; j:=j-1 end; cont[j]:=aux1; ci[j]:=aux2;

end;

end;

Page 34: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 34

procedure tresmasvisitadas(var todos:grupoturistas; var tresciud:tres; var ww:integer);

vari,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;

Page 35: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 35

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;

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;

Page 36: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 36

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;

Page 37: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 37

BEGIN {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

Page 38: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 38

Run-time errorsApplications generated by Free Pascal might generate Run-time error when certain abnormal conditionsare detected in the application. This appendix lists the possible run-time errors and givesinformation 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 beenreached. 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 severalreasons:• 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 alreadyexists.• 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 anotherdisk 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.

Page 39: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 39

Run-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 anumeric 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 getthis 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.

Page 40: Clase 13 COMPUTACION 2009 COMPUTACION 2009 5/7/2015 Computación - Fac. Ingeniería - UNMDP2 Tipos de Datos PASCAL Estructurados Simples Primitivos No

04/21/23Computación - Fac. Ingeniería

- UNMDP 40

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 AssertErrorProc procedural variable was installed.