the question :- In the file 'CUSTOMER.DAT' there are 100 records with the structure customer .In another file 'TRANSACTIONS.DAT' there are several records with the structure trans
The element trans_type contains D/W indicating deposit or withdrawal of amount. Write a program to update 'CUSTOMER.DAT' file, ie, if the trans_type is 'D' then update the balance of 'CUSTOMER.DAT' by adding amount to balance for the corresponding accno. Similarly, if trans_type is 'W' then subtract the amount from balance.
I am able to compare line by line data in a file if i open file in txt mode ie in "r" and "w" but when i open in binary "rb" "wb" ,i can't compare line by line data. How to do it?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct customer
{
int accno ;
char name[30] ;
float balance ;
};
struct trans
{
int accnum ;
char trans_type ;
float amount ;
} ;
int main()
{
FILE *fs,*ft,*f1;
struct customer c;
struct trans tr;
fs = fopen("customer.txt","rb");
if (fs==NULL)
{
printf("Can't open file.");
exit(1);
}
f1 = fopen("transactions.txt","rb");
if (f1==NULL)
{
printf("Can't open file.");
exit(2);
}
ft = fopen("temp.txt","wb");
if (ft==NULL)
{
printf("Can't open file.");
exit(3);
}
while(fread(&c,sizeof(c),1,fs)==1)
{
while(fread(&tr,sizeof(tr),1,f1)==1)
{
if( tr.accnum == c.accno && tr.trans_type == 'D')
{
c.balance = c.balance + tr.amount;
break;
}
else if( tr.accnum == c.accno && tr.trans_type == 'W')
{
if(c.balance - tr.amount < 100)
break;
else
c.balance = c.balance - tr.amount;
break;
}
}
fwrite(&c,sizeof(c),1,ft);
}
fclose(fs);
fclose(f1);
fclose(ft);
remove("customer.txt");
rename("temp.txt","customer.txt");
return 0;
}
The data sample in customer.txt is
1 aman 456.45
2 loma 199.40
3 shail 15
The data sample in transactions.txt is
1 D 500.89
3 W 51.00
2 W 40
where D is deposit and w is withdraw
File data is encoded as text . Do not read the data with fread()
which expects a fixed length binary data.
Open the file in text mode and read the line of data with fgets()
.
char buffer[100];
if (fgets(buffer, sizeof buffer, fs)) {
// Now process the data
Let us process the data with sscanf()
. Look for malformed data. Use " %n"
to record the offset of trailing non-white-space text.
struct trans tr;
int n = 0;
sscanf(buffer, "%d %c %f %n", &tr.accnum, &tr.trans_type, &tr.amount, &n);
// Was scanning incomplete or extra junk at the end or non W,D?
if (n == 0 || buffer[n] != 0 ||
(tr.trans_type != 'W' && tr.trans_type != 'D')) {
fprintf(stderr, "Bad input <%s>\n", buffer);
break;
}
// Use `t`.
}
When it is time to write, use sufficient precision to write a distinctive float
.
fpritnf(fs, "%d %c %.9g\n", t.accnum, t.trans_type, t.amount);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.