<span style="font-size:18px;"># include <stdio.h>
# include <stdlib.h>
long size; /* */
typedef struct LogData
{
long logid; // ID
char logdate[11]; //
char lognote[15]; //
double charge; //
double balance; //
} dat;
//
int inputchoice()
{
int maychoice;
printf("
Enter your choice:
");
printf("1-Add a new cash
2-List All Cash LOG
3-Query Last Cash LOG
0-End program
");
scanf("%d", &maychoice);
return maychoice;
}
//
long getLogcount(FILE *cfptr)
{
long begin, end, logcount;
fseek(cfptr, 0L, SEEK_SET); // int fseek(FILE * stream,long offset,int whence);
// whence :
// SEEK_SET offset 。SEEK_CUR offset 。
// SEEK_END offset 。
// whence SEEK_CUR SEEK_END , offset
begin = ftell(cfptr); // 。 stream
fseek(cfptr, size, SEEK_END);
end = ftell(cfptr);
logcount = (end-begin) / size - 1;
return logcount;
}
//
void ListAllLog(FILE *cfptr)
{
dat log;
fseek(cfptr, 0l, SEEK_SET);
fread(&log, size, 1, cfptr); // log: size: , 1: , size cptr:
printf("logid logdate lognote charge balance
");
while(!feof(cfptr)) //feof , 0 , 0, clearerr()
{
printf("%6ld%-11s%-15s%10.2lf%10.2lf
", log.logid, log.logdate, log.logdate, log.charge, log.balance);
}
}
//
void QueryLastLog(FILE *cfptr)
{
dat log;
long logcount;
logcount = getLogcount(cfptr);
if (logcount>0) //
{
fseek(cfptr, size*(logcount-1), SEEK_SET); //
fread(&log, size, 1, cfptr);
printf("The last log is:
");
printf("logid-6ld
logdate:%-11s
lognote:%-15s
", log.logid, log.logdate, log.lognote);
printf("charge:%-10.2lf
balance:%-10.2lf
", log.charge, log.balance);
}
else printf("no logs in file
");
}
//
void AddNewLog(FILE *cfptr)
{
dat log, lastlog;
long logcount;
printf("Input Logdate(format:2006-01-01):");
scanf("%s", log.logdate);
printf("Input Lognote:");
scanf("%s", log.lognote);
printf("Input charge:income+ and expend -:");
scanf("%lf", &log.charge);
logcount = getLogcount(cfptr);
if (logcount>0)
{
fseek(cfptr, size*(logcount-1), SEEK_SET);
fread(&lastlog, size, 1, cfptr);
log.logid = lastlog.logid+1;
log.balance = log.charge + lastlog.balance;
}
else
{
log.logid = 1;
log.balance = log.charge;
}
rewind(cfptr);
printf("logid = %ld
", log.logid);
fwrite(&log, sizeof(dat), 1, cfptr);
}
FILE *openfile(char *openmod)
{
FILE *fp;
if ((fp = fopen("cashbox.dat", openmod)) == NULL)
{
printf("Cannot Open file
");
exit(0);
}
return (fp);
}
int main(void)
{
FILE *fp;
int choice;
while((choice=inputchoice()) != 0)
{
switch(choice)
{
case 1:
fp = openfile("ab+");
AddNewLog(fp);
case 2:
fp = openfile("rb");
ListAllLog(fp);
case 3:
fp = openfile("rb");
QueryLastLog(fp);
break;
default:
printf("Input Error");
break;
}
}
if (fclose(fp))
{
printf("Cannot close the fiel!
");
exit(0);
}
return 0;
}</span>