我编写了下面这段代码:
#include<ctype.h>
#include<stdio.h>
#define SIZE 3
//#define PIN "0123456"
struct worker_type
{
char num[8];
char name[12];
}work[SIZE];
void save()
{
FILE *fp;
int i;
if((fp=fopen("text","wb"))==NULL)
{
printf("cannot open file\n");
}
for(i=0;i<SIZE;i++)
if(fwrite(&work[i],sizeof(struct worker_type),1,fp)!=1)
printf("file write error\n");
fclose(fp);
}
void showall()
{
int i;
FILE *fp;
fp=fopen("text","rb");
for(i=0;i<SIZE;i++)
{
fread(&work[i],sizeof(struct worker_type),1,fp);
printf("%s %s\n",work[i].num,work[i].name);
}
fclose(fp);
}
void main()
{ int m;
scanf("%d",m);
switch(m)
{
case 1: {
int i;
for(i=0;i<SIZE;i++)
scanf("%s %s",work[i].num,work[i].name);
save();
}break;
case 2: showall();break;
}
}
编译通过,不过运行时,选择时提示内存不可读的错误,如果将main改成:
void main()
{
int i;
for(i=0;i<SIZE;i++)
scanf("%s %s",work[i].num,work[i].name);
save();
showall();
}
就完全没有问题了。但我希望选择运行,要如何实现呢??