文件的输入输出问题,输出出来后,信息乱码
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct
{
FILE *pfile;
char fname[20];
}file={NULL,"information"};
void list_file(void);
int main(void)
{
int len;
int age=0;
char ch='y';
char name[20];
if(!(file.pfile=fopen(file.fname,"wb")))
{
printf("\nCannnot write file\n");
exit(1);
}
do
{
fflush(stdin);
printf("Please input name(letter<20)\n");
gets(name);
printf("Please input age\n");
scanf("%d",&age);
len=strlen(name);
fwrite(&len,sizeof len,1,file.pfile);
fwrite(name,len,1,file.pfile);
fwrite(&age,sizeof(age),1,file.pfile);
printf("\nDo you want to enter another(y/n)\n");
scanf(" %c",&ch);
}
while(tolower(ch)=='y');
fclose(file.pfile);
list_file();
system("pause");
return 0;
}
void list_file(void)
{
char name[20];
int age;
int len;
if(!(file.pfile=fopen(file.fname,"rb")))
{
printf("\nCannot read file\n");
exit(1);
}
while(fread(&len,sizeof len,1,file.pfile))
{
if(len<=20)
{
fread(name,len,1,file.pfile);----------------------用strlen(name)返回 3(假设输入qwe);
printf("%-20s",name);------------------------------再次用strlen(name)返回 31;
fread(&age,sizeof age,1,file.pfile);
printf(" %d\n",age);
}
else
{
printf("Name too long,cannot show it\n");
system("pause");
}
}
fclose(file.pfile);
}







