Final Exam C Program
Final Exam C Program
Final Exam C Program
I. File :
Library
Example :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
Structure
Example :
struct product{
int code;
char name[20];
float price;
};
Write
Example :
FILE *fp;
product a[100];int n;
fp=fopen(name,"wb");
if(fp==NULL){
return;
printf("Number of product:");scanf("%d",&n);
for(int i=0;i<n;i++){
printf("code:");scanf("%d",&a[i].code);
printf("name:");fflush(stdin);gets(a[i].name);
printf("price:");scanf("%f",&a[i].price);
fwrite(a,sizeof(product),n,fp);
fclose(fp);
Read
Example :
FILE *fp;
product a[100];int n;
fp=fopen(name,"rb");
if(fp==NULL){
return;
fseek (fp,0,SEEK_END);
n=ftell(fp)/sizeof(product);
rewind(fp);
fread(a,sizeof(product),n,fp);
fclose(fp);
for(int i=0;i<n;i++)
printf("%d\t%s\t%.2f\n",a[i].code,a[i].name,a[i].price);
}
Append
Example:
FILE *fp;
product a[100];int n;
fp=fopen(name,"ab");
if(fp==NULL){
return;
printf("Number of product:");scanf("%d",&n);
for(int i=0;i<n;i++){
printf("code:");scanf("%d",&a[i].code);
printf("name:");fflush(stdin);gets(a[i].name);
printf("price:");scanf("%f",&a[i].price);
fwrite(a,sizeof(product),n,fp);
fclose(fp);
Update
Example:
FILE *fp;
fp=fopen(name,"rb");
if(fp==NULL){
return;
fseek (fp,0,SEEK_END);
n=ftell(fp)/sizeof(product);
rewind(fp);
fread(a,sizeof(product),n,fp);
fclose(fp);
printf("Code to update:");scanf("%d",&c);
for(int i=0;i<n;i++)
if(a[i].code==c){pos=i;break;}
printf("New product:\n");
printf("New code:");scanf("%d",&x.code);
printf("New name:");fflush(stdin);gets(x.name);
printf("New price:");scanf("%f",&x.price);
a[pos]=x;
fp=fopen(name,"wb");
if(fp==NULL){
return;
fwrite(a,sizeof(product),n,fp);
fclose(fp);
}
Remove
Example
FILE *fp;
fp=fopen(name,"rb");
if(fp==NULL){
return;
fseek (fp,0,SEEK_END);
n=ftell(fp)/sizeof(product);
rewind(fp);
fread(a,sizeof(product),n,fp);
fclose(fp);
fp=fopen(name,"wb");
if(fp==NULL){
return;
printf("Code to remove:");scanf("%d",&c);
for(int i=0;i<n;i++)
if(a[i].code!=c)fwrite(&a[i],sizeof(product),1,fp);
fclose(fp);
}
Main :
Example :
void main(){
char name[20],select;
printf("write(w),read(r),append(a),remove(v),update(u):\n");
scanf("%c",&select);
switch(select){
write(name);break;
read(name);break;
append(name);break;
update(name);break;
remove(name);break;
getch();
}
II. ប្រៀបធៀបលក្ខណៈខុសគ្នា ៖