Code C\C++: Xử lý file văn bản
/* File
Bai tap 1.
- Nhap vao 1 day so nguyen co n so (2<n<10)
- Ghi day so vua nhap vao file Mang1.txt trong o E:\
- Tim gia tri lon nhat, ghi vao cuoi file Mang1.txt
- Doc du lieu trong file Mang1.txt
*/
#include<stdio.h>
#include<conio.h>
// khai bao
int a[10],n;
FILE *f;
// Nhap mang
void NhapMang(){
printf("\n Nhap so phan tu ");
do{ printf("\n n= ");
scanf("%d",&n);
if (n<2||n>10)
printf("\n Nhap lai n!");
}while (n<2||n>10);
// Nhap day
printf("\n Nhap day: ");
for(int i=0;i<n;i++)
{
printf("\n a[%d]=",i); scanf("%d",&a[i]);
}
}
// Ghi vao file
void GhiFile(){
f=fopen("E:\\Mang1.txt","w");
for(int i=0;i<n;i++)
fwrite(&a[i],sizeof(int),1,f);
fclose(f);
printf("\n Da ghi xong!");
}
//Tim max
int Max(){
int max=a[0];
for(int i=1;i<n;i++)
if(max<a[i]) max=a[i];
return max;
}
// Ghi gia tri max vao file
void GhiMax(){
f=fopen("E:\\Mang1.txt","a");
// dua con tro file ve cuoi file
fseek(f,SEEK_END,0);
int max=Max();
fwrite(&max,sizeof(int),1,f);
fclose(f);
printf("\n Da ghi xong gia tri Max !");
}
// doc du lieu tu file
void DocFile(){
printf("\n Doc du lieu tu file: \n ");
f=fopen("E:\\Mang1.txt","r");
int t;
for(int i=0;i<n;i++){
fread(&t,sizeof(int),1,f);
printf("%d ;",t);
}
// doc gia tri max
fread(&t,sizeof(int),1,f);
printf("\n Max: %d",t);
}
// Ham main
int main(){
NhapMang();
GhiFile();
GhiMax();
DocFile();
getch();
return 0;
}
//----CLICK HERE->>>Tài liêu hướng dẫn xử lý File trong C\C++