Difference between revisions of "File Handling In Pascal/es"

From Free Pascal wiki
Jump to navigationJump to search
Line 30: Line 30:
 
Mediante la supresión de los errores de entrada/salida utilizando ({$I-}) los resultados de la operación con ficheros se meterán en la variable IOSResult. Este es un [[Cardinal|cardinal (number) type]]. Cada uno de los distintos numeros indicarán los diferentes errores obtenidos. Estos códigos de error se pueden consultar en la documentación [http://www.freepascal.org/docs-html/rtl/system/ioresult.html].
 
Mediante la supresión de los errores de entrada/salida utilizando ({$I-}) los resultados de la operación con ficheros se meterán en la variable IOSResult. Este es un [[Cardinal|cardinal (number) type]]. Cada uno de los distintos numeros indicarán los diferentes errores obtenidos. Estos códigos de error se pueden consultar en la documentación [http://www.freepascal.org/docs-html/rtl/system/ioresult.html].
  
===File procedures===
+
=== Procedimientos de fichero ===
These file handling procedures and functions are located in unit system. See the FPC documentation for more details: [http://www.freepascal.org/docs-html/rtl/system/index-5.html Reference for 'System' unit].
 
  
* '''AssignFile''' (prevent the use of the older '''Assign''' procedure) - Assign a name to a file
+
Estas funciones y  procedimientos de manejo de ficheros se encuentran en la unit 'system'. Ver la documentación de FPC para más detalles:
* '''Append''' - Opens an existing file for appending data to end of file and editing it
+
 
* '''BlockRead''' -  Read data from an untyped file into memory
+
[http://www.freepascal.org/docs-html/rtl/system/index-5.html Reference for 'System' unit].
* '''BlockWrite''' - Write data from memory to an untyped file
+
 
* '''CloseFile''' (prevent the use of the older '''Close''' procedure) - Close opened file
+
* '''AssignFile''' (previene del uso del antiguo procedimiento '''Assign''' ) - Asigna un nombre a un fichero.
* '''EOF''' - Check for end of file
+
* '''Append''' - Abre un fichero ya existente en el modo añadir al final del mismo.
* '''Erase''' - Erase file from disk
+
* '''BlockRead''' -  Lee un bloque de datos de un fichero sin tipo poniéndolo en memoria.
* '''FilePos''' - Get position in file
+
* '''BlockWrite''' - Escribe un bloque de datos desde la memoria hacia un fichero sin tipo.
* '''FileSize''' - Get size of file
+
* '''CloseFile''' (previene el uso del procedimiento antiguo '''Close''' ) - Cierra un fichero que está abierto.
* '''Flush''' - Write file buffers to disk
+
* '''EOF''' - Chequea si se ha llegado al final del fichero (EOF=End Of File), devuelve true si ha llegado y false si todavía no.
* '''IOResult''' - Return result of last file IO operation
+
* '''Erase''' - Borra un fiechro del disco.
* '''Read''' - Read from a text file
+
* '''FilePos''' - Retorna da la posición en que nos encontramos dentro del fichero.
* '''ReadLn''' - Read from a text file and go to the next line
+
* '''FileSize''' - Retorna el tamaño del fichero.
* '''Reset''' - Opens a file for reading
+
* '''Flush''' - Escribe los buffers de fichero a disco.
* '''Rewrite''' - Create a file for writing
+
* '''IOResult''' - Retorna el resultado de la última operación de entrada/salida (I/O) de ficheros.
* '''Seek''' - Change position in file
+
* '''Read''' - Lee desde un fichero tipo texto.
* '''SeekEOF''' - Set file position to end of file
+
* '''ReadLn''' - Lee desde un fichero tipo texto (una línea entera) y salta a la siguiente línea.
* '''SeekEOLn''' - Set file position to end of line
+
* '''Reset''' - Abre un fichero para lectura.
* '''Truncate''' - Truncate the file at position
+
* '''Rewrite''' - Crea un fichero para escritura.
* '''Write''' - Write variable to a file
+
* '''Seek''' - Cambia a una posición dentro del fichero.
* '''WriteLn''' - Write variable to a text file and go to a new line
+
* '''SeekEOF''' - Sitúa la posición dentro del fichero en su final.
 +
* '''SeekEOLn''' - sitúa la posición del fichero al final de la línea.
 +
* '''Truncate''' - Trunca el fichero en la posición indicada.
 +
* '''Write''' - Escribe una variable en el fichero.
 +
* '''WriteLn''' - Escribe una variable a un fichero de texto y salta a una nueva línea.
  
 
===Example===
 
===Example===

Revision as of 17:56, 24 June 2015

العربية (ar) English (en) español (es) suomi (fi) français (fr) 日本語 (ja) русский (ru) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

Descripción

Algo que necesitan conocer todos los programadores es como trabajar con ficheros. Los ficheros se utilizan para almacenar datos de forma persistente, i.e. almacenar datos de manera que puedan ser retornados en un momento posterior sin tener que volver a crearlos. Los ficheros pueden utilizarse para almacenar configuraciones de usuario, reportes de error, medidas o resultados de cálculos, etc. Esta página explica lo básico sobre manejo de ficheros.

Estilo del procedimiento antiguo

Cuando se utilizan ficheros en el modo clásico de Pascal (no orientado a objetos) se puede utilizar el tipo 'TextFile' (o simplemente 'Text') para almacenar texto, que está estructurado típicamente en líneas. Cada línea finaliza con una marca de fin de línea (EOL=End Of Line). En este tipo de fichero se pueden almacenar tanto cadenas (strings) como números (integer, real...) formateados además de la forma que más nos convenga. Estos ficheros pueden posteriormente abrirse para visualizarlos o editarlos mismamente con el IDE de Lazarus o cualquier otro editor de texto.

Para propósitos específicos se puede crear un tipo de fichero personalizado que puede almacenar únicamente un tipo de dato. Por ejemplo:

...
type
  TIntegerFile  = file of integer;  // Permite escribir únicamete números de tipo entero (integer) al fichero.
  TExtendedFile = file of extended; // Permite escribir úncamente números de tipo real al fichero.
  TCharFile     = file of char;     // Permite escribir únicamente caracteres simples al fichero.

Manejo de errores de Entrada/Salida

El I/O error handling flag o flag (bandera) de Entrada/Salida (I/O -> Input/Output) indica al compilador como manejarse con las situaciones de error: lanzar una excepción o almacenar el resultado de la entrada/salida en la variable IOResult.

El flag de manejo del error de entrada/salida es una directiva del compilador. Para habilitarlo/deshabilitarlo escribimos:

{$I+} // Los errores generarán una excepción EInOutError (por defecto)
{$I-} // Suprime los errores de entrada/salida: chequea la veriable IOResult para saber su código de error.

Mediante la supresión de los errores de entrada/salida utilizando ({$I-}) los resultados de la operación con ficheros se meterán en la variable IOSResult. Este es un cardinal (number) type. Cada uno de los distintos numeros indicarán los diferentes errores obtenidos. Estos códigos de error se pueden consultar en la documentación [1].

Procedimientos de fichero

Estas funciones y procedimientos de manejo de ficheros se encuentran en la unit 'system'. Ver la documentación de FPC para más detalles:

Reference for 'System' unit.

  • AssignFile (previene del uso del antiguo procedimiento Assign ) - Asigna un nombre a un fichero.
  • Append - Abre un fichero ya existente en el modo añadir al final del mismo.
  • BlockRead - Lee un bloque de datos de un fichero sin tipo poniéndolo en memoria.
  • BlockWrite - Escribe un bloque de datos desde la memoria hacia un fichero sin tipo.
  • CloseFile (previene el uso del procedimiento antiguo Close ) - Cierra un fichero que está abierto.
  • EOF - Chequea si se ha llegado al final del fichero (EOF=End Of File), devuelve true si ha llegado y false si todavía no.
  • Erase - Borra un fiechro del disco.
  • FilePos - Retorna da la posición en que nos encontramos dentro del fichero.
  • FileSize - Retorna el tamaño del fichero.
  • Flush - Escribe los buffers de fichero a disco.
  • IOResult - Retorna el resultado de la última operación de entrada/salida (I/O) de ficheros.
  • Read - Lee desde un fichero tipo texto.
  • ReadLn - Lee desde un fichero tipo texto (una línea entera) y salta a la siguiente línea.
  • Reset - Abre un fichero para lectura.
  • Rewrite - Crea un fichero para escritura.
  • Seek - Cambia a una posición dentro del fichero.
  • SeekEOF - Sitúa la posición dentro del fichero en su final.
  • SeekEOLn - sitúa la posición del fichero al final de la línea.
  • Truncate - Trunca el fichero en la posición indicada.
  • Write - Escribe una variable en el fichero.
  • WriteLn - Escribe una variable a un fichero de texto y salta a una nueva línea.

Example

A full example of handling a text file of type TextFile:

program CreateFile;

uses
 Sysutils;

const
  C_FNAME = 'textfile.txt';

var
  tfOut: TextFile;

begin
  // Set the name of the file that will be created
  AssignFile(tfOut, C_FNAME);

  // Use exceptions to catch errors (this is the default so not absolutely requried)
  {$I+}

  // Embed the file creation in a try/except block to handle errors gracefully
  try
    // Create the file, write some text and close it.
    rewrite(tfOut);

    writeln(tfOut, 'Hello textfile!');
    writeln(tfOut, 'The answer to life, the universe and everything: ', 42);

    CloseFile(tfOut);

  except
    // If there was an error the reason can be found here
    on E: EInOutError do
      writeln('File handling error occurred. Details: ', E.ClassName, '/', E.Message);
  end;

  // Give feedback and wait for key press
  writeln('File ', C_FNAME, ' created if all went ok. Press Enter to stop.');
  readln;
end.

Now open the file in any text editor and you will see the above text written to it! You can test the error handling by running the program once, then set the file to read-only and run the program again.

Note that exception handling was used as that is an easy way to perfom multiple file operations and handling the errors. You could also use {$I-}, but then you would have to check IOResult after each operation and modify your next operation.

Here's how appending more text to a textfile works:

program AppendToFile;

uses
 Sysutils;

const
  C_FNAME = 'textfile.txt';

var
  tfOut: TextFile;

begin
  // Set the name of the file that will receive some more text
  AssignFile(tfOut, C_FNAME);

  // Embed the file handling in a try/except block to handle errors gracefully
  try
    // Open the file for appending, write some more text to it and close it.
    append(tfOut);

    writeln(tfOut, 'Hello again textfile!');
    writeln(tfOut, 'The result of 6 * 7 = ', 6 * 7);

    CloseFile(tfOut);

  except
    on E: EInOutError do
     writeln('File handling error occurred. Details: ', E.Message);
  end;

  // Give feedback and wait for key press
  writeln('File ', C_FNAME, ' might have more text. Press enter to stop.');
  readln;
end.

Reading a textfile:

program ReadFile;

uses
 Sysutils;

const
  C_FNAME = 'textfile.txt';

var
  tfIn: TextFile;
  s: string;

begin
  // Give some feedback
  writeln('Reading the contents of file: ', C_FNAME);
  writeln('=========================================');

  // Set the name of the file that will be read
  AssignFile(tfIn, C_FNAME);

  // Embed the file handling in a try/except block to handle errors gracefully
  try
    // Open the file for reading
    reset(tfIn);

    // Keep reading lines until the end of the file is reached
    while not eof(tfIn) do
    begin
      readln(tfIn, s);
      writeln(s);
    end;

    // Done so close the file
    CloseFile(tfIn);

  except
    on E: EInOutError do
     writeln('File handling error occurred. Details: ', E.Message);
  end;

  // Wait for the user to end the program
  writeln('=========================================');
  writeln('File ', C_FNAME, ' was probably read. Press enter to stop.');
  readln;
end.