Desarrollo de aplicaciones informáticas


Programación en C


E/S UTILIZANDO REGISTROS O BLOQUES EN C

Compilador Utilizado: Turbo C/C++ 3.0

La manipulación de información en archivos es muy importante en la programación de ciertas aplicaciones en C, para lo cual es necesario saber programar las tareas básicas (añadir, modificar eliminar y consultar) sobre registros en un archivo de datos.

Por lo anterior se escriben y explican fragmentos de códigos en C que son utilizados en el DEMO que se preparo como ilustración, que espero que sea de gran utilidad para aquellos programadores que deseen saber sobre este asunto y no queden mal al preguntarle ¿ Como puedo hacerle para que mi programa pueda manipular un archivo de datos?.

Se supone que el lector investigara sobre las funciones de E/S definidas para el sistema de archivos ANSI en C utilizadas aquí.

Sea la siguiente declaración de la estructura del registro a guardar:

struct Registro {

int Field;

// Un Campo tipo entero llamado Field

// ... Definicion de otros Campos

};

Ahora puede declararse una variable para almacenar el registro como sigue:

struct Registro Reg; // Declarar Registro

int SIZEBYTES=sizeof(struct Registro); // Tamaño en bytes de la

estructura

Lo que sigue es describir las rutinas necesarias.

Rutina: Filesize

Descripción: Devuelve el tamaño en bytes del archivo apuntado por P_File.

Código:

long Filesize(FILE *P_File)

{ long Pos,Length;

Pos = ftell(P_File); // Guardar el posicion actual del

puntero

fseek(P_File, 0L, SEEK_END); // Ir al final del Fichero

Length = ftell(P_File); // Almacenar el Tamaño del Fichero

fseek(P_File,Pos, SEEK_SET); // Restablecer puntero

return (Length);

}

Rutina: Crear_Abrir

Descripción: Crea o abre un archivo para Lectura/Escritura, regresando e l puntero de fichero determinado por Name. En caso de algún error regresa NULL.

Código:

FILE *Crear_Abrir(const char Name[])

{ FILE *Pf;

// Intentar abrirlo para Lectura/Escritura

if((Pf=fopen(Name,"r+b"))==NULL) // Crearlo para Lectra/Escritura

Pf=fopen(Name,"w+b");

return(Pf);

}

Rutina: Truncate

Descripción: Eliminar el ultimo registro físicamente del archivo apuntado por Pf.

Código:

void Truncate(const char Name[],FILE *Pf)

{ long L; // Longitud en bytes

int Pa; // Para el manejador de E/S tipo UNIX

L=Filesize(Pf)-(long) SIZEBYTES; //Ubicar el en ultimo registro de Name

fclose(Pf); //Cerrar el flujo para abrir Name usando

Pa=open(Name,O_RDWR); // E/S tipo UNIX para usar chsize y

chsize(Pa,L); // Recortar el ultimo registro

close(Pa); // Cerrar Name usando E/S tipo UNIX

Pf=Crear_Abrir(Name); // Para abrir Name usando E/S tipo ANSI

}

El código para crear o abrir un fichero es el siguiente:

file=Crear_Abrir("Mio.dat"); // Crear un fichero llamado "Mio.dat"

donde Aqui file debe ser declarado como FILE *file;

El código para añadir un registro al fichero es el siguiente:

fseek(file,0L,SEEK_END); // Ir al final del Fichero

fwrite(&Reg,SIZEBYTES,1,file); // Escribir un registro

fflush(file); // Fisicamente en el fichero

Una forma sencilla de eliminar un registro es remplazar el registro a borrar por el ultimo y luego recortar o eliminar el ultimo registro del fichero. Por ejemplo para eliminar el tercer registro el código seria:

desp=(long) Filesize(file)-(long) SIZEBYTES;

// Calcular el desplazamiento en bytes del ultimo registro

fseek(file,desp,SEEK_SET); // Posicionarse en el para

fread(&Reg,SIZEBYTES,1,file); // leerlo

desp=(long)(3-1)*SIZEBYTES; // Aqui (3-1) es para ilustrar el

// desplazaamiento del Tercer registro

// del fichero, en Gral. es (N-1)

fseek(file,desp,SEEK_SET); // Posicionarse en el para borrarlo

fwrite(&Reg,SIZEBYTES,1,file); // remplazandolo por el ultimo registro

Truncate("Mio.dat",file); // y borrando fisicamente el ultimo

Para mayor detalle estudie el código fuente completo incluido en el DEMO.

// Demo para manejo de E/S tipo ANSI usando registros

// Elaborado por : Francisco Ovando Diaz

// Fecha : Marzo de 1999

// Compilador Usado: Turbo C/C++ 3.0 de Borland International,inc.

#include<stdio.h>

#include <fcntl.h>

#include <io.h>

// Declaracion de la estructura del registro

struct Registro {

int Field; // Un Campo tipo entero llamado Field

// ... Definicion de otros Campos

};

struct Registro Reg; // Declarar Registro

int SIZEBYTES=sizeof(struct Registro); // Tamaño en bytes de la estructura

long Filesize(FILE *P_File)

{ long Pos,Length;

Pos = ftell(P_File); // Guardar el posicion actual del

puntero

fseek(P_File, 0L, SEEK_END); // Ir al final del Fichero

Length = ftell(P_File); // Almacenar el Tamaño del Fichero

fseek(P_File,Pos, SEEK_SET); // Restablecer puntero

return (Length);

}

FILE *Crear_Abrir(const char Name[])

{ FILE *Pf;

// Intentar abrirlo para Lectura/Escritura

if((Pf=fopen(Name,"r+b"))==NULL) // Crearlo para Lectra/Escritura

Pf=fopen(Name,"w+b");

return(Pf);

}

void Truncate(const char Name[],FILE *Pf)

{ long L; // Longitud en bytes

int Pa; // Para el manejador de E/S tipo UNIX

L=Filesize(Pf)-(long) SIZEBYTES; //Ubicar el en ultimo registro de Name

fclose(Pf); //Cerrar el flujo para abrir Name usando

Pa=open(Name,O_RDWR); // E/S tipo UNIX para usar chsize y

chsize(Pa,L); // Recortar el ultimo registro

close(Pa); // Cerrar Name usando E/S tipo UNIX

Pf=Crear_Abrir(Name); // Para abrir Name usando E/S tipo ANSI

}

void main()

{ FILE *file; // Declaracion de un apuntador a un fichero

int i;

long desp;

file=Crear_Abrir("Mio.dat"); // Crear un fichero llamado "Mio.dat"

//===================================================================

// LAS SIGUIENTES LINEAS DE CODIGO ES PARA AÑADIR 10 REGISTROS EN EL

// FICHERO

//===================================================================

fseek(file,0L,SEEK_END); // Ir al final del Fichero

for(i=1; i<=10; i++) // Guardar 10 registros en el Fichero

{

Reg.Field=i; // Asignar i al campo Field

fwrite(&Reg,SIZEBYTES,1,file); // Escribir un registro

fflush(file); // Fisicamente en el fichero

}

// ===============================================================

// LAS SIGUINTES SON PARA BORRAR EL TERCER REGISTRO DEL FICHERO

// REMPLAZANDOLO POR EL ULTIMO Y ELIMINANDO EL ULTIMO FISICAMENTE

// ===============================================================

desp=(long) Filesize(file)-(long) SIZEBYTES;

// Calcular el desplazamiento en bytes del ultimo registro

fseek(file,desp,SEEK_SET); // Posicionarse en el para

fread(&Reg,SIZEBYTES,1,file); // leerlo

desp=(long)(3-1)*SIZEBYTES; // Aqui (3-1) es para ilustrar el

// desplazaamiento del Tercer registro

// del fichero, en Gral. es (N-1)

fseek(file,desp,SEEK_SET); // Posicionarse en el para borrarlo

fwrite(&Reg,SIZEBYTES,1,file); // remplazandolo por el ultimo registro

Truncate("Mio.dat",file); // y borrando fisicamente el ultimo

// Nota 1: Para hacer algun cambio a un registro,solo hay que

//posicionarse en el y remplazarlo por el nuevo.

// =========================================================

// IMPRIMIR EL CONTENIDO DE TODOS LOS REGISTROS DEL FICHERO

// =========================================================

fseek(file,0L,SEEK_SET); // Ir al inicio del archivo

fread(&Reg,SIZEBYTES,1,file); // Leer un registro

while(!feof(file)) // Mientra NO sea el fin del fichero

{

printf("%d \n",Reg.Field); // Imprimir el contenido del campo

// Field

fread(&Reg,SIZEBYTES,1,file); // Leer un registro

}

// Nota 2: Para saber cuantos registros hay en fichero, se calcula de

// la sig. manera: NREG =(long) (Filesize(file)/SIZEBYTES)-1;

fclose(file); // Cerrar el fichero

}

4

UNIVERSIDAD JUÁREZ AUTONOMA DE TABASCO Licenciatura en Computación 3 Semestre

Mayo de 1995.




Descargar
Enviado por:Fod
Idioma: castellano
País: México

Te va a interesar