个人小金库,方便记账哦
//本程序主要用到结构和文件的基本操作。
//很实用的小程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct cash
{
long id;//事件的id号
char date[11];//事件的发生日期
char note[15];//事件的名称
double charge;//支出或收入的金额
double balance;//现在的所剩金额
};
long size;
void menu();//选择菜单
long getcount(FILE *fp);//返回事件的个数
void list(FILE *fp);//列出账目
void query(FILE *fp);//查询
void add(FILE *fp);//增加新记录
int main()
{
char mima[10]="123456";
char inputmima[10];
FILE *fp;
int choice;
system("COLOR 8a");
if ((fp=fopen("cash.txt","ab+"))==NULL)
{
printf("打开文件失败!\n");
exit(0);
}
printf("我 的 个 人 小 金 库\n\n\n");
printf("访问请输入密码:");
scanf("%s",&inputmima);
while(strcmp(mima, inputmima) != 0)
{
printf("密码错误!退出");
exit(0);
}
system("cls");
size=sizeof(struct cash);
while(1){
menu();
printf("请输入选择(1-4):");
scanf("%d",&choice);
switch(choice)
{
case 1:
add(fp);
break;
case 2:
list(fp);
break;
case 3:
query(fp);
break;
case 4:
exit(0);
default:
printf("input error");
break;
}
system("cls");
}
return 0;
}
void menu()
{
printf(" ----------------------------------------------\n");
printf("|1.add a new cash log || 2. list all cash log | \n");
printf("|3.query last cast log || 4 exit cash program |\n");
printf(" ----------------------------------------------\n");
}
long getcount(FILE *fp)
{
long begin,end,countlog;
fseek(fp,0L,SEEK_SET);
begin=ftell(fp);
fseek(fp,size,SEEK_END);
end=ftell(fp);
countlog=(end-begin)/size-1;
return countlog;
}
void list(FILE *fp)
{
struct cash log;
long countlog;
fseek(fp,0L,SEEK_SET);
fread(&log,size,1,fp);
printf(" id | date | note | charge | balance\n");
while (!feof(fp))
{
printf("%3d %11s%15s %8.2lf%8.2lf\n",log.id,log.date,log.note,log.charge,log.balance);
fread(&log,size,1,fp);
}
system("pause");
}
void query(FILE *fp)
{
struct cash log;
long countlog;
countlog=getcount(fp);
if (countlog>0)
{
fseek(fp,size*(countlog-1),SEEK_SET);
fread(&log,size,1,fp);
printf("the last log is :\n");
printf(" id | date | note | charge | balance\n");
printf("%3d %11s%15s %8.2lf%8.2lf\n",log.id,log.date,log.note,log.charge,log.balance);
}
else
printf("文件中没记录\n");
system("pause");
}
void add(FILE *fp)
{
struct cash log,lastlog;
long countlog;
printf("输入日期:");
scanf("%s",log.date);
printf("输入事件:");
scanf("%s",log.note);
printf("输入支出(-)或收入(+):");
scanf("%lf",&log.charge);
countlog=getcount(fp);
if (countlog>0)
{
fseek(fp,size*(countlog-1),SEEK_SET);
fread(&lastlog,size,1,fp);
log.id=lastlog.id+1;
log.balance=log.charge+lastlog.balance;
}
else
{
log.id=1;
log.balance=log.charge;
}
rewind(fp);
printf("id=%ld\n",log.id);
fwrite(&log,sizeof(struct cash),1,fp);
}