C程序执行有问题
# include <stdio.h># include <ctype.h>
# include <string.h>
# include <stdlib.h>
const int MAXLEN = 30;
void listfile(char *filename);
int main(void)
{
char *filename = "D:\\temp\\zhang.bin";
char name[30];
size_t length = 0;
int age = 0;
char answer = 'y';
FILE *pfile = fopen(filename,"wb+");
do
{
fflush(stdin);
printf("Enter a name less than %d characters:",MAXLEN);
gets(name);
printf("Enter the age of %s:",name);
scanf(" %d",&age);
length = strlen(name);
fwrite(&length,sizeof(length),1,pfile);
fwrite(name,sizeof(char),length,pfile);
fwrite(&age,sizeof(age),1,pfile);
printf("Do you want to enter another(y or n)?");
scanf(" %c",&answer);
}while (tolower(answer) == 'y');
fclose(pfile);
listfile(filename);
return 0;
}
void listfile(char *filename)
{
size_t length = 0;
char name[30];
int age = 0;
char format[20];
sprintf(format ,"\n%%-%ds Age:%%4d",MAXLEN);
FILE *pfile = fopen(filename,"rb");
printf("\nThe contents of %s are:",filename);
while(fread(&length,sizeof(length),1,pfile));
{
if(length+1 > MAXLEN)
{
printf("\nName too long.");
exit(1);
}
fread(name,sizeof(char),length,pfile);
name[length+1] = '\0';
fread(&age,sizeof(age),1,pfile);
printf(format,name,age);
}
fclose(pfile);
}
编译可以通过,但执行却出现乱码,跪求大侠解决方案。