criedjoker 2015-10-19 11:10 采纳率: 80%
浏览 1375

C语言文件读取问题,求帮忙看看

想用程序实现输入一个人姓名和电话号码并写入文件,然后读取显示文件中的数据。
但输出如图:图片说明输出最后两个重复,不知是哪里出错,求大神帮忙看看。
程序代码如下:
#include
#include
#include
#include

typedef struct man
{
char name[20];
char first_name[20];
long phone_number;
} man;

int main(void)
{
FILE* pfile=NULL;//调用文件的指针
man* temp=(man*)malloc(sizeof(man));//存储输入数据的临时变量
char* filename="man.bin";//文件名
char ch=0;//控制是否继续输入的变量
int leng=0;//用来存储字符串长度

/*输入数据并把它们写入文件*/
while(true)
{
if(!(pfile=fopen(filename,"ab")))
{
fprintf(stderr,"不能打开文件\n");
exit(1);
}
printf("请输入名字:");
gets(temp->name);
fflush(stdin);
leng=strlen(temp->name);
fwrite(&leng,sizeof(int),1,pfile);
fwrite(temp->name,sizeof(char),leng,pfile);
printf("请输入姓氏:");
gets(temp->first_name);
fflush(stdin);
leng=strlen(temp->first_name);
fwrite(&leng,sizeof(int),1,pfile);
fwrite(temp->first_name,sizeof(char),leng,pfile);
printf("请输入电话:");
scanf("%ld",&temp->phone_number);
fflush(stdin);
fwrite(&temp->phone_number,sizeof(long),1,pfile);
printf("若想结束输入,请输入n:");
scanf("%c",&ch);
fflush(stdin);
if(tolower(ch)=='n')
break;
fclose(pfile);
}

/*检测用户是否要列出所有数据,若要则列出所有数据*/
printf("\n若要列出文件中所有信息,请输入s:");
scanf("%c",&ch);
fflush(stdin);
if(tolower(ch)=='s')
{
  if(!(pfile=fopen(filename,"rb")))
    {
        fprintf(stderr,"文件不能打开\n");
        exit(1);
    }
    rewind(pfile);
    while(!feof(pfile))
    {
        fread(&leng,sizeof(int),1,pfile);
        fread(temp->name,sizeof(char),leng,pfile);
        temp->name[leng]='\0';
        fread(&leng,sizeof(int),1,pfile);
        fread(temp->first_name,sizeof(char),leng,pfile);
        temp->first_name[leng]='\0';
        fread(&temp->phone_number,sizeof(long),1,pfile);
        printf("%s %s的电话号码为%ld\n",temp->name,temp->first_name,temp->phone_number);
    }
    fclose(pfile);
}

    free(temp);//释放内存
    temp=NULL;

return 0;

}

  • 写回答

5条回答 默认 最新

  • qq_32140585 2015-10-19 11:21
    关注

    同问听见了李经理惊惊拖

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名