You are on page 1of 4

I. BI TP V FILE NH PHN 1 /* Ghi n so nguyen vao file va doc ra tu file*/ #include <stdio.h> #include <conio.h> #include <stdlib.

h> #define MAX 5 void main(void) { FILE *f; int i, ia[MAX], ib[MAX]; for (i = 0; i < 10; i++) { printf("Nhap vao mot so: "); scanf("%d", &ia[i]); } if((f = fopen("array.dat", "wb")) == NULL) { printf("Khong the mo file!\n"); exit(0); } fwrite(ia, sizeof(ia), 1, f); //ghi mang vao file fclose(f); f = fopen("array.dat", "rb"); fread(ib, sizeof(ib), 1, f); //doc mang tu file for (i = 0; i < 10; i++) printf("%d ", ib[i]); fclose(f); getch(); }

- FILE *f; : khai bo bin con tr f c kiu cu trc FILE.

o fi e f

- if(f = fopen("arry.dat", "wb") == NULL) : l cu lnh m tp tin c tn arry.dat mode "w" (ghi ) d ng "b" (nh phn), sau khi lnh ny thc hin xong tr v d ng con tr FILE v gn cho f, nu kt qu tr v = NULL th khng th m c tp tin, tp tin m mode "w" nu trn a c sn tp tin ny th ni dung ca n s b ghi , nu cha c th tp tin s c t o mi. - fwrite(&i, sizeof(int), 1, f); : ghi thng tin vo tp tin, thng tin c ghi vo mi ln l mt s nguyn i Hm ny c 4 i s: a ch ghi cu trc,kch thc ca cu trc v s cu trc s ghi, sau cng l con tr tr ti tp tin. - fclose(f); : ng tp tin. f = fopen("arry.dat", "rb"); : m tp tin c tn arry.dat mode "r" c) d ng "b" (nh phn). Tp tin phi c sn trn a

2:

, c structure

/* Danh sach nhan vien */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #define MAX 50 void main(void) { FILE *f; struct nhanvien { int manv; char hoten[30]; }; nhanvien snv[MAX], snv1[MAX]; char ctam[10]; int i, in; printf("Nhap vao so nhan vien: "); gets(ctam); in = atoi(ctam); //Nhap danh sach nhan vien va ghi vao file if((f = fopen("struct.dat", "wb")) == NULL) { printf("Khong the mo file!\n"); exit(0); } fwrite(&in, sizeof(int), 1, f); //ghi so nhan vien vao file for(i = 0; i < in; i++) { printf("Nhap vao ma nhan vien thu %d: ", i + 1); gets(ctam); snv[i].manv = atoi(ctam); printf("Nhap vao ho ten: "); gets(snv[i].hoten); fwrite(&snv[i], sizeof(nhanvien), 1, f); //ghi tung nhan vien vao file } fclose(f); //doc danh sach nhan vien tu file va in ra f = fopen("struct.dat", "rb"); 3

fread(&in, sizeof(int), 1, f); //doc so nhan vien for(i = 0; i < in; i++) { fread(&snv1[i], sizeof(nhanvien, 1, f); //doc tung nhan vien in ra man hinh printf("%5d %s\n", snv[i].manv, snv[i].hoten); } getch(); } II. BI TP V FILE TEXT.

V d 1: Nhp mng

You might also like