/*运行程序按1可以创建并且在一个文本文件里写入保存数据,再重新运行,按3,无法读出,而且原文本文件的内容都空了*/#include<stdio.h>#include<stdlib.h>#include<math.h>#define N 100struct product{ int num; //设备编号 char type[20]; //设备类 型};FILE *fp;void input(struct product *p);void scan(struct product *p); int system(const char *string);int main(){ struct product pro[N]; int i; int number=0; if((fp=fopen("test1.txt","wt"))==NULL) { printf("不能打开文件.\n"); exit(1); } fwrite(&number,sizeof(int),1,fp); fclose(fp); printf("* 1.添加新设备 3.浏览设备信息 *\n"); printf("请用数字选择你需要的功能:"); scanf("%d",&i); system("cls"); //清屏操作 switch(i) { case 1: input(pro); break; case 3: scan(pro); break; } return 0;}void input(struct product *p) //写入{ char str[20]; int n; if((fp=fopen("test1.txt","wt+"))==NULL) { printf("不能打开文件.\n"); exit(1); } rewind(fp); fread(&n,sizeof(int),1,fp); n++; rewind(fp); fwrite(&n,sizeof(int),1,fp); fclose(fp); if((fp=fopen("test1.txt","at+"))==NULL) { printf("不能打开文件.\n"); exit(1); } printf("输入设备编号:"); scanf("%s",str); p->num=atoi(str); fwrite(&(p->num),sizeof(int),1,fp); printf("输入设备类型:"); scanf("%s",p->type); fwrite(p->type,sizeof(char),1,fp); fclose(fp);}void scan(struct product *p) //浏览 读出{ int i,n; int num; char type[20]; if((fp=fopen("test1.txt","rt"))==NULL) { printf("error on delete!"); exit (1); } rewind(fp); fread(&n,sizeof(int),1,fp); for(i=0;i<n;i++) { fread(&num,sizeof(int),1,fp); fread(type,sizeof(char),1,fp); printf("%d %s \n",num,type); } fclose(fp);}
- 1 回答
- 0 关注
- 1760 浏览
添加回答
举报
0/150
提交
取消