kiem tien, kiem tien online, kiem tien truc tuyen, kiem tien tren mang
Thứ Tư, 5 tháng 3, 2014


/* Ví dụ sử dùng FILE trong C\C++
Viết chương trình:
 - Nhập vào 2 số nguyên a, b
 - Ghi 2 số nguyên a,b vào file bai1.txt
 - Đọc dữ liệu từ file bai1.txt, tính tổng, hiệu, tích, thương
 - Ghi kết quả vào file bai1.txt
 - Đọc dữ liệu từ file bai1.txt, in kết quả ra màn hình.

*/
#include<stdio.h>
#include<conio.h>
int a,b, tong, hieu, tich, thuong;
FILE *f;
// Nhap 2 so nguyen a,b
void Nhap(){
 printf("\n Nhap 2 so a,b: ");
 printf("\n a= ");
 scanf("%d",&a);
 printf("\n b= ");
 scanf("%d",&b);
}
// ghi a,b vao file bai1.txt
void GhiDuLieu(){
  //  mo file de ghi
  f=fopen("E:\\bai1.txt","w");
  // ghi a, b vao file
  fwrite(&a,sizeof(a),1,f);
  fwrite(&b,sizeof(b),1,f);
  // dong file
  fclose(f);
}
// Doc du lieu tu file bai1.txt
void DocDuLieu(){
// mo file de doc
f=fopen("E:\\bai1.txt","r");
// Doc du lieu tu file bai1.txt
int x,y;// chua du lieu doc ra
fread(&x,sizeof(x),1,f);
fread(&y,sizeof(y),1,f);
// tinh tong, hieu, tich, thuong
tong=x+y;
hieu=x-y;
   tich=x*y;
thuong=x/y;
// dong file
fclose(f);
}
// ghi ket qua vao file
void GhiKQ(){
 // mo file de ghi them
 f=fopen("E:\\bai1.txt","a");
 // di chuyen ve cuoi file
 fseek(f,0,SEEK_END);
 // ghi them tong, hieu,tich,thuong vao file
 fwrite(&tong,sizeof(tong),1,f);
 fwrite(&hieu,sizeof(hieu),1,f);
 fwrite(&tich,sizeof(tich),1,f);
 fwrite(&thuong,sizeof(thuong),1,f);
 //
 fclose(f);
}
// Doc ket qua tu file baiq.txt
void DocKQ(){
// mo file de doc
f=fopen("E:\\bai1.txt","r");
// dua con tro ve dua file
rewind(f);
printf("\n KET QUA DOC TU FILE bai1.txt ");
int t;// chua ket qua
fread(&t,sizeof(t),1,f); printf("\n a= %d",t);
fread(&t,sizeof(t),1,f); printf("\n b= %d",t);
fread(&t,sizeof(t),1,f); printf("\n tong= %d",t);
fread(&t,sizeof(t),1,f); printf("\n hieu= %d",t);
fread(&t,sizeof(t),1,f); printf("\n tich= %d",t);
fread(&t,sizeof(t),1,f); printf("\n thuong= %d",t);
fclose(f);
}
// ham main
int main(){
  Nhap();
  GhiDuLieu();
  DocDuLieu(); // doc và tinh
  GhiKQ(); // ghi them vao file
  DocKQ();
 getch();
 return 0;
}

[Tải Code Chương trình tại đây (Lưu ý: Sau 5s, click Bỏ qua quảng cáo - Skin Ad)]
05 Mar 2014

0 nhận xét:

Đăng nhận xét

:) :)) ;(( :-) =)) ;( ;-( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ $-) (b) (f) x-) (k) (h) (c) cheer
Click to see the code!
To insert emoticon you must added at least one space before the code.

domain, domain name, premium domain name for sales

Bài đăng phổ biến