El lenguaje C tiene la capacidad de abrir archivos
secuenciales en 4 formas diferentes:
PRIMERA:Los datos pueden ser escritos 6 lefdos caracter por
caracter.
SEGUNDA:Los datos pueden ser escritos 6 lefdos como Strings.
TERCERA:Los datos pueden ser escritos 6 lefdos como una
coleccién de valores mixtos, que pueden contener valores,
caracteres, Strings, nimeros de punto flotante y entero:
CUARTA: Los datos pueden ser escritos 6 lefdos en un formato
llamado "record" 6 "block". Esto es usado cuando se tiene
una sucesi6n similar de campos de datos, como lo son las
estructuras. Este tipo es ideal para bases de datosPARA ABRIR UN ARCBIVO, Gl ILIZA LA INSTRUCCION
BIVO, GENERALMENTE 88 UTILIU!
‘Tiene el siguiente formato:
fopen (NOMBRE DEL--ARCAIVO, MODO)
El nombre del archivo debe contener un méximo de 8 caracteres con
3 caracteres de extensién.
Los modos son los siguientes.
"rc" _Abre pé lectura. El archivo debe existir.
"w" Abre para escritura. Si el archivo existe, su contenido se
borraré. Si no existe, ser& creado.
"a Abre para afiadidura. El material sera afiadido al final de
una archivo existente, o un nuevo archivo ser4 creado.
crt" Abre para lectura y escritura. £1 archivo debe existir.
“wt* Rbre para Yeetorh:y itura. Si el archivo existe, su
contenido se borrar&. .
vat" Abre para lectura y escritura. Si el archivo no existe ser&
creado.
Archivo de caracteres
=e, ee ceracteres.
Ejesta forma: lain! i6n se quarda caracter
2 Por caracter
Y se jbtiene de lamisna manefa. Los conandos utilizados eon gete
A continuaéién se encuentra un programa que gua:
C eda dj
un arene encl Totsatovaa! watt 2ragrtmm, gu0 guarde datos a
etree? giemplos que leen los datos del archivo creado on ot
priner ejemplo.
Etemplor
J+ PROGRAMA QUE ESCRIBE CARACTER RACTER 1
Hinclude POR CARACTER A OW aRcuIVO */
void main (void)
FILE *fptr;
char ch;
clrscr();
Brint£(* Este prograna e
Spt = topen -Peapannagesceibe eerecteres @ un archivo \n");
while((ch=getche())1='\r')
pute(chy fptr) ¢
getehe()s
) Belose (sper);/* PROGRAMA QUE LEE CARACTER POR CARACTER DE UN ARCHIVO +/
include
told mein (void)
fing *fpts;
int ch;
elrecr();
petnee ("Bate Programa lee caracte!
"7
‘plrefopen(*PRUEBA.TXP", r=);
while((ch = getc(fptr)) 1=Z0F)
printf("te", ch)?
geteh();
fclose(fptr);
de un archivo ya creado
Existe el la instruccién NULL que nos indica si existe error al
momento de leer el archivo. £1 siguiente programa ea un éjeliplo
de como se puede utilizar.
/* LEE CARACTER POR CARACTER DE UN ARCHIVO, REVISA ERROR DE
incr
include
finclude
int main(void)
t
FILE *fptr;
char ch;
elrscr();
if ((fptr-fopen("textfile.txt","r")) =
NULL)
printf("No puedo abrir e] archivo textfile.txt");
exit (1);
4
while((ch = getc(fptr))1=E0F)
Print£("te",ch));
getche();
felose(fptr);
return(0);jcentra 1
lo es un programa que con ’
2 gente anteriores en un nend de opciones y utiliza
para cada una de las opciones
//*PROGRAMA QUE ESCRIBE Y¥ LEE CARACTER POR CARACTER UN-ARCHIVO */
finclude
void main(void)
t char opeion;
do
t clrscr();
Eint£(*Ment de opciones. \n“);
Printf(sten Bsccivure de on archivo.\n")7
print£(*2.- Lectura
Print£("3.- Salida.
Print£("Elija su opcién
epcion = getch();
switch (opeion)
t
“dase ‘1’: escritura(); break; }
case ‘2':( lectura(); break; }
case ‘3/:( break; }
}
Jwhile(opeiont=*3");
ycritura (void)
{ FILE *apuntador;
char nom_archivo(13},ch;
elrscr(}7 ~ mes ts
printf(*\n Deme e1 nombre del archivo al que va
gets(nom_archivo);
apuntador = fopen(nom_archivo, *w*);
while((chegetche())1=7\r')
pute(ch, apuntador) ;
getche();
fc.0se(apuntador);
return 0;
}
Jectura(void)
{ FILE *apuntador;
char nom_archivo[13),ch;
elrscr()7
printt("\n Deme el nombre del archivo que va a leer: “
gets (nom_archivo); recone
spuntador = fopen(nom_archivo, “r“);
/hile((ch = getc(apuntador)) 1=E0F}
Printf(*tc",ch);
getch();
felose(apuntador);
Feturn 0; }
escribir: “);ARCHIVO DE STRINGS
En esta forma la informacion se guarda etring por string
se obtiene de la misma manera.Se entiende por string una cadena
Ge caracteres de longitud definida. Los comandos utilizados son
fgets y fpute.
Ejomplost
[+ PROGRAMA QUE ESCRIBE STRINGS A UN ARCHIVO */
Hinclude
void main (void)
‘prug «tpte:
char string}81);
elrscr();
fptr=fopen ("PRUEBA.TXT", *w") ;
printf("Este programa escribe strings en’un’ archivo \n");
printf("Teclear después de cada frase\n. *)}
while(strien(gets (string) )>0)
t
fputs
fputs|
ring, fptr);
"\n", fptr);
)
getche();
felose(fptr);
}
/* PROGRAMA QUE LEE STRING DE UN ARCHIVO */
finclude 7
void main (void)
FILE *iptr;
char string/81);
elrscr();
printf("Saca strings de un archivo \n*
{ptr = fopen(*PRUEBA.TXT™,"r");
vhile( fgets(string, 0, fptr) /=NULL)
printf ("¥s", string);
getche(); ‘
felose(fptr);/* PROGRAMA QUB BSCRIBE Y LEE STRINGS DE UN ARCHIVO +/
include
void main(void)
t.
char opeiony
do
{ elrscr (zs ea
intf£("Meni de opei :
Bene tent se eesende on dechive.
printf(*2.- Lectura de un archivo.\n");
print£("3.- Salida.\n")?
printf("Elija su opcién: *)7
opcion = getche();
switch (opeion)
case ‘1’:{ escritura(); break; }
case ‘2':{ lectura(); break; }
case ‘3':{ break; } -
,
Jwhile(opeiont=’3*);
}
escritura()
{ FILE *apuntador;
char string(81],nom_archivo(13};
elrser();
printf("Deme el nombre del archivo que va a escribir: *);
gets (nom_archivo) ; )
apuntador = fopen(nom_archivo, "w");
print£(*Teclear despues de cada frase\n “);
while(strlen(gets(string))>0) :
fputs(stritig /apuntador) ;
fputs("\n",apuntador);
}
getche();
fclose(apuntador) ;
return 07
t
Jectura()
{ FILE *apuntador;
char string(81],nom_archivo[13];
elrscr();-
printf(*Deme el nombre de el archivé que va a leer: “);
gets(nom_archivo);
apuntador = fopen(nom_archivo,"r);
while( fgets(string, 80, apuntador) 1=NULL)
printf("ts", string);
getche();..—
fclose(apuntador);
return 0; }ARCHIVOS FORMATEADOS 0 MIXTOS
Los comandos utilizados en ests forma eon fprintf y fscanf.
tipo de archivo, los (= Pueden, ser de diferentes
ya sea enteros, caracteres, strings’ o flotantes. Para
werdar o cargar cualquier dato se debe especificar eu tipo,
Seilizando los especificadores de formato.
Bjemplos:
/* FORATEADO 0 MIXTO */
7+ PROGRAMA QUE ESCRIBE DATOS BN UN ARCHIVO BN FORMA MIXTA */
tinclude
void main(void) srenivott2}3
prox *tpers
char name(40)7
int code;
float height;
elrscr();
fptr= fopen(*PRUEBA. TXT", "w");
do
{
printf(™ Teclee Nombre,Cédigo y Altura ")z
Scant ("ts 4d tf", name, scode,ébeight)7 0 2"
fprintf(fptr, "ts td %f",. code, height) ;
}
while(strlen(name)>1);
getche();
felose(fptr) ;
}
J/* PROGRAMA PARA LEER LOS DATOS DE o
finclude States
void main (void)
t
FILE *fptr;
char name (40);
int code;
float height;
fptrsfopen(“PRUBBA.TXT", *r") ;
printf£("Nombre — Cédigo Altura \nv);
while( fscanf(fptr,"ts td 8", name, be i
le( facen {,hame, &code, éheight) I=EOF)
gebrsnttt ad 4.2£\n", name, code, height);
felose(fptr);JgoGRAHA QUE ESCRIBE ¥ LEE DATOS EN UN ARCHIVO EN F. ary,
pi
(include
void main(vodd)
t char opcions
° Arect(); en
‘ crintt(Hend de opedones.\n")i i
ESE ont opto: enaves ary:
printf(+2.- Lectura de in archivo. \n");
printf("3.- Salida.\n")7 |
printf("Blija su opeiént “)7
epcion = getche()7 -
switch (opcion
Mopege "1" s{ escritura(); brea
case ‘2’:{ lectura(); break; }
case '3':{ break; }
) }while(opcion!='3");
?
escritura()
( FILE *apuntador;
char name(40},nom_archivo(13];
int code; }
float height;
elrscr();
printf("Deme el nombre del archivo al que va a escribir: ~);
gets (nom_archivo);
apuntador= fopen(nom_archivo, "w");
do
{ print£(" Teclee Nonbre,Cédigo y Altura “);
scanf ("ts td tf",name,écode, éheight) ;
fprint£(apuntador, "ted 8£",name, code, height);
} while(strlen(name)>1) ;.
getche(,
fclose(apuntador);
return 0;
Jectura ()
{ FILE *apuntador;
char name(40],nom_erchivo[13};
int code;
float height;
elrser();
print£("Deme el nombre del archivo que v:
gets(nom_archivo); Renee ante
@puntador = fopen(nom_archivo,"r*);
printt("Nombre Cédigo Altura \n-) >
prince gsea, @Puntedor, "As Ad S£*, name, Scode, height) BOF)
gegiimteC Ne i) §.24\n"/name,code, height) ;
felose(apuntador,
return(Oye yn)?ARCHIVO EN FORMA DE RECORDS
9 utilizados son fwrite y fre
o utiliza estructuras para d
te mismo formato
toe comand
gchives o0 el, $3
de ‘cada “record” «
ae Gives aleatorios
nic 1
utiliza para los
«PROGRAMA QUE BSCRIBE‘YALBE “RECORDS: DE UN ARCHIVO ”
‘include
Linelude
void main(void)
{
char opcion;
do
{
elrect()?
print£("Meni de opciones.\n");
printé(“1.- Escribir un archivo. \n"
printf(*2.- Leer un archivo.\n");
printf(*3.- Salida.\n")7
Printt (“Escoja su opcion: *);
épcion = getche()7
switch (opcion)
t
case ‘1/:{ escritura(); break; }
case ‘2':{ lectura(); break; }
case ‘3/:{ break; }
pwhidefopeionte’3!)7
scritura()
€
struct
{
double height;
char name(40]7
int agnurb;
agents
char nunstr(81),non_archivo/ 13,
char op; 7 fal
FILE *apuntador;
print (“Dene el ‘
printf(*Deme el nombre del archivo a:
gets (nom_archivo); neve er duel weal enerdbtrd! ")
{f'(lapustador = fopen (nom_archi =
ee fopen (nom_archivo, “wb") NULL)
printf (“No puedo abrir el acchi
exit()? rir el achive");
,do
(orint£(*\n Introduzca un nombre?
gets(agent -name);
printf("\n Introdi
gets(numstr); - - :
agent .agnumb-atoi (numstr) 7 ay
print#("\n‘Thtroduaca’gu altura: *)7 |
gets (numstr) :agent -heightwatof(numstr)?
fwrite(sagent,izeof (agent), 1/apuntador);
printf("Desea anadir otro agente(S/N): ")é
op=getche();
oti
uzca un numero: “)i
}
while(op=='5' || ope='s‘)i
fclose(apuntador) ;
return(0);
}
lectura()
struct
{
double height;
char name [40];
int agnumb;
} agent;
char numstr[81},nom_archivo[13];
char op;
FILE sapuntador;
clrser();
print£("Dame el nombre del archivo que vas a leer: *);
gets(nom_archivo);
if ((apuntador=fopen (nom_archivo, "rb"))==NULL)
print£("No puedo abrir el archivo");
exit(1);
}
while ( fread(sagent, sizeof (agent) ,1,apuntador)==1)
{
print£("\n Nombre : ts\n",agent.name);
Print£("\n Numero : %d\n",agent .agnumb) ;
Print£("\n Altura : %.2f\n",agent .height) ;
}
getche();
felose(apuntador);
Feturn(0);