Trabajar con archivos: algunos ejemplos

Veamos unos ejemplos de cómo trabajar con archivos en Delphi.

Puedes consultar los apuntes principales en este artículo.

Manipulación básica de archivos de texto

Ejemplo de manipulación de un fichero de texto:

AssignFile(miArchivo, 'Test.txt');  //asignar fichero
//Abrir el fichero para escribir
ReWrite(miArchivo) / Reset(miArchivo); / Append(miArchivo);
WriteLn(miArchivo, 'Hello');
WriteLn(miArchivo, 'World');
// Abrir el fichero para leer
Reset(miArchivo);
while not Eof(miArchivo) do
begin
  ReadLn(miArchivo, text);
  ShowMessage(text);
end;
CloseFile(miArchivo);

Manipulación de archivos de texto para almacenamiento de datos tipados

Ejemplo de lectura y escritura de datos tipados (en este caso, de tipo Record) en un fichero de texto:

type
  TCustomer = Record
    name : string[20];
    age  : Integer;
    male : Boolean;
  end;
var
    miArchivo : File of TCustomer;  // A file of customer records
    customer : TCustomer;          // A customer record variable
begin
    // Try to open the Test.cus binary file for writing to
    AssignFile(miArchivo, 'Test.cus');
    ReWrite(miArchivo);  // Write a couple of customer records to the file
    customer.name := 'Fred Bloggs';
    customer.age  := 21;
    customer.male := true;
    Write(miArchivo, customer);
    customer.name := 'Jane Turner';
    customer.age  := 45;
    customer.male := false;
    Write(miArchivo, customer);
    // Close the file
    CloseFile(miArchivo);
    // Reopen the file in read only mode
    FileMode := fmOpenRead;
    Reset(miArchivo);
    // Display the file contents
    while not Eof(miArchivo) do
    begin
      Read(miArchivo, customer);
      if customer.male
      then ShowMessage('Man with name '+customer.name+
                      ' is '+IntToStr(customer.age))
      else ShowMessage('Lady with name '+customer.name+
                      ' is '+IntToStr(customer.age));
    end;
    // Close the file for the last time
    CloseFile(miArchivo);
  end;

Manipulación de archivos binarios para almacenamiento de datos tipados

Ejemplo de lectura y escritura de datos tipados (en este caso, de tipo Record) en un fichero binario:

var
  myFile : File;
  byteArray : array[1..8] of byte;
  oneByte : byte;
  i, count : Integer;
begin
  // Try to open the Test.byt file for writing to
  AssignFile(myFile, 'Test.byt');
  ReWrite(myFile, 4);   // Define a single 'record' as 4 bytes
  // Fill out the data array
  for i := 1 to 8 do
    byteArray[i] := i;
  // Write the data array to the file
  BlockWrite(myFile, byteArray, 2);   // Write 2 'records' of 4 bytes
  // Fill out the data array with different data
  for i := 1 to 4 do
    byteArray[i] := i*i;              // Value : 1, 4, 9, 16
  // Write only the first 4 items from the data array to the file
  BlockWrite(myFile, byteArray, 1);   // Write 1 record of 4 bytes
  // Close the file
  CloseFile(myFile);
  // Reopen the file for reading only
  FileMode := fmOpenRead;
  Reset(myFile, 1);   // Now we define one record as 1 byte
  // Display the file contents
  // Start with a read of the first 6 bytes. 'count' is set to the
  // actual number read
  ShowMessage('Reading first set of bytes :');
  BlockRead(myFile, byteArray, 6, count);
  // Display the byte values read
  for i := 1 to count do
    ShowMessage(IntToStr(byteArray[i]));
  // Now read one byte at a time to the end of the file
  ShowMessage('Reading remaining bytes :');
  while not Eof(myFile) do
  begin
    BlockRead(myFile, oneByte, 1);   // Read and display one byte at a time
    ShowMessage(IntToStr(oneByte));
  end;
  // Close the file for the last time
  CloseFile(myFile);
end;

Nota: es más que recomendable utilizar bloques try-except-finally al trabajar con ficheros. Las instrucciones de apertura, lectura, escritura, etc. pueden lanzar excepciones IO. Y para evitar dejar el archivo abierto siempre meter la instrucción de cierre (CloseFile) dentro del bloque finally.

Guarda   |   Imprime   |   Recomienda
  • email
  • Print
  • PDF
  • RSS
  • Google Bookmarks
  • Technorati
  • Meneame
  • Digg
  • TwitThis
  • MySpace
  • Yahoo! Bookmarks
  • del.icio.us
  • Facebook
  • Bitacoras.com
  • Live
  • StumbleUpon
  • Wikio
  • Netvibes
  • BarraPunto

Otros artículos de esta serie:

Publicar un Comentario

Si es la primera vez que escribes, tu comentario será moderado por un administrador.

Con el fin de garantizar un ambiente de debate respetuoso, no se permitirán comentarios:

  • insultantes, difamatorios, racistas, sexistas, y/o discriminatorios
  • excesivamente críticos con otros participanes
  • que no aporten nada, sin sentido o repetidos
  • con enlaces considerados publicidad o spam
  • con material protegido por derechos de autor
*
*