You are on page 1of 10

CHNG IX

FILE
I.

1.

a file ra a:
M file:
Muc ich cua phn nay la xy dng
mt file mi ghi thng tin ln o hoc
khi ng mt file a tn tai b
sung thm d liu.
m mt file ta s dung ham
fopen()

Cu phap cua ham nh sau:


FILE *fpa, *fopen();
char *path_name;
char *type
fpa = fopen(path_name,type);
Chc nng:
La m mt file c ch ra bi
path_name, vi kiu m mt file la type, khi
m xong th gan gia tr o cho con tro kiu
FILE.
Trong o:
path_name: La ng dn n file

w: M file ghi mi.


a: M file b sung.
r: M file oc.
2. Ghi thng tin ln file a m:
ghi thng tin ln file a m, ta dung
ham chun
fprintf();
Cu phap cua ham:
fprintf(Con tro kiu FILE, dong iu
khin[, danh sach
i s]);
Chc nng: Ghi vao file

3. ong file

Vic nay c thc hin nh s


dung ham
fclose() hoc fcloseall()
Cu phap:
int fclose(Con tro kiu FILE)
Hoc
int fcloseall()
V du:
Vit chng trinh xy dng mt file
mi co tn la Matran va ghi ln o cac
phn t cua ma trn a c 4x4.

#include "stdio.h"
main()
{
FILE *fpp, *fopen();
int a[4][4];
int i,j,m;
fpp=fopen("matran","w");
for (i=0;i<4;++i)
for (j=0;j<4;++j)
{
printf("a[%d,%d]= ",i,j);
scanf("%d",&m);
a[i][j]=m;
}

for (i=0;i<4;++i)
for (j=0;j<4;++j)
fprintf(fpp,"%d\n",a[i][j]);
fclose(fpp);
return 0;
}
II. oc vao t file
1. M file
S dung ham fopen()
Cu phap hoan toan ging phn trn ch
khac la phn type la r

2. oc thng tin t mt file vao b nh

oc thng tin t file a m vao b


nh ta dung ham chun:
fscanf()
Cu phap:
fscanf(Con tro kiu FILE, dong iu
kin[,
danh sach i s]);
3. ong file
Ging phn trn.

V du:
Vit lai chng trnh v du trn , sau
o oc file va in ra man hnh.
#include "stdio.h"
main()
{
FILE *fpp, *fopen();
int a[4][4];
int i,j,m;
fpp=fopen("matran","w");

for (i=0;i<4;++i)
for (j=0;j<4;++j)
{
printf("a[%d,%d]= ",i,j);
scanf("%d",&m);
a[i][j]=m;
}
for (i=0;i<4;++i)
for (j=0;j<4;++j)
fprintf(fpp,"%d\n",a[i][j]);
fclose(fpp);

fpp=fopen("matran","r");
for (i=0;i<4;++i)
{
for (j=0;j<4;++j)
{
fscanf(fpp,"%d",&m);
printf("%d ",m);
}
printf("\n");
}
getch();
return 0;
}

You might also like