fscanf 函数读取的问题
程序代码:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> typedef struct info info; struct info { int age; char name[20]; char cellphone[12]; char qqid[12]; info *next; }; void get_name (info *current) { printf ("请输入联系人姓名:"); fgets (current->name,20,stdin); int len=strnlen_s (current->name,sizeof (current->name)); if (current->name[len-1]=='\n') { current->name[len-1]='\0'; } } void get_qqid (info *current) { printf ("请输入当前联系人的QQ号码:"); fgets (current->qqid,12,stdin); int len=strnlen_s (current->qqid,sizeof (current->qqid)); if (current->qqid[len-1]=='\n') { current->qqid[len-1]='\0'; } } void write_file (FILE *pfile,char *filename,info *first,info *current,info *previous) { current=first; while (current!=NULL) { if (fopen_s (&pfile,filename,"wb+")) { printf ("打开文件失败"); exit (1); } int len=strnlen_s (current->name,sizeof (current->name)); fprintf (pfile,"%4d",len); fwrite (current->name,sizeof (char),len,pfile); fwrite (current->cellphone,sizeof (char),11,pfile); len=strnlen_s (current->qqid,sizeof (current->qqid)); fprintf (pfile,"%-4d",len); fwrite (current->qqid,sizeof (char),len,pfile); fprintf (pfile,"%4d",current->age); previous=current; current=current->next; free (previous); previous=NULL; } first=NULL; fclose (pfile); } void get_person (info *current) { get_name (current); fflush (stdin); putchar (10); printf ("请输入当前联系人的年龄:"); scanf_s ("%d",¤t->age,sizeof (int)); fflush (stdin); putchar (10); printf ("请输入当前联系人的手机号:"); fgets (current->cellphone,12,stdin); fflush (stdin); putchar (10); get_qqid (current); fflush (stdin); } bool find_info (FILE *pfile,char *filename) { int len; int flen; bool find=false; info temp; char temp_name[20]; char cell[12]={'\0'}; char qq[12]={'\0'}; if(fopen_s (&pfile,filename,"rb+")) { printf ("打开文件失败。"); exit (1); } printf ("请输入要修改联系人的姓名:"); fflush (stdin); fgets (temp_name,20,stdin); while (1) { fscanf (pfile,"%4d",&len); fread (temp_name,sizeof (char),len,pfile); fread (cell,sizeof (char),11,pfile); fscanf (pfile,"%d",&flen); fread (qq,sizeof (char),flen,pfile); fscanf (pfile,"%4d",&temp.age); if (strcmp (temp_name,temp.name)==0) { printf ("联系人已经找到."); find =true; break; } if (feof (pfile)) { break; } } return find; } int main () { info *first=NULL; info *current=NULL; info *previous=NULL; char buf[100]; char answer='\0'; bool find=false; FILE *pfile=NULL; char *filename="info.bin"; for ( ; ; ) { if (first==NULL) { printf ("请输入第一个联系人的信息:"); putchar (10); } else { printf ("是否继续输入? y or n :"); scanf_s ("%c",&answer,sizeof (char)); fflush (stdin); if (tolower (answer)=='n') { break; } } current=(info*)malloc (sizeof (info)); if (first==NULL) { first=current; } if (previous!=NULL) { previous->next=current; } get_person (current); current->next=NULL; previous=current; } write_file (pfile,filename,first,current,previous); find=find_info (pfile,filename); system ("pause"); return 0; }
在find_info函数中的fscanf(pfile,“%d“,&flen)处出错,flen为一个随机值,这是为什么?求解释