文件
来源:互联网 发布:蓝光宝盒是什么软件 编辑:程序博客网 时间:2024/04/25 17:53
#include<stdio.h>
#include<stdlib.h>
struct goods_info
{
int num;
char name[12];
int count;
float price;
};
void save(struct goods_info *p);
void inGoodsInf(struct goods_info *p);
void read(void);
main()
{
FILE *fp;
char ch,flag=1;
struct goods_info goods;
if((fp=fopen("goods.dat","a+b"))==NULL)
{
printf("对不起,不能打开这个文件!/n");
exit(-1);
}
fclose(fp);
while(flag)
{
system("cls");
printf("/n/n");
printf("/t/t=============商品信息系统=============/n/n");
printf("/t/t/t1.商品信息录入/n");
printf("/t/t/t2.商品信息读取/n");
printf("/t/t/t3.退出/n/n");
printf("请输入功能号:");
scanf("%d",&ch);printf("/n");
switch(ch)
{
case 1:
do
{
inGoodsInf(&goods);
save(&goods);
printf("是否继续输入(y/n)?");
fflush(stdin);
ch=getchar();
}while(ch=='y'||ch=='Y');
break;
case 2:
read();
break;
case 3:
flag=0;
break;
default:
printf("输入错误!!/n");
}
}
system("cls");
return 0;
}
void inGoodsInf(struct goods_info *p)
{
system("cls");
printf("/n/t==============商品信息录入=============/n/n");
printf("请输入商品编号:");
scanf("%d",&p->num);
printf("请输入商品名称:");
scanf("%s",&p->name);
printf("请输入商品数量:");
scanf("%d",&p->count);
printf("请输入商品单价:");
scanf("%f",&p->price);
}
void save(struct goods_info *p)
{
FILE *fp;
if((fp=fopen("goods.dat","rb++"))==NULL)
printf("对不起,不能打开这个文件!/n");
else
{
fseek(fp,0,SEEK_END);
fwrite(p,sizeof(struct goods_info),1,fp);
fclose(fp);
}
}
void read()
{
FILE *fp;
struct goods_info goods;
if((fp=fopen("goods.dat","rb"))==NULL)
{
printf("对不起,不能打开这个文件!/n");
return;
}
system("cls");
printf("/n/t/t============商品信息============/n/n");
printf("商品编号/t商品名称/t商品数量/t商品单价/n");
while(!feof(fp))
{
fread(&goods,sizeof(struct goods_info),1,fp);
if(feof(fp))continue;
printf("%d/t/t%s/t/t%d/t/t%.2f/n",goods.num,goods.name,goods.count,goods.price);
}
printf("/n请按回车键返回主菜单...");
getchar();
getchar();
fclose(fp);
}