当前位置: 技术问答>linux和unix
一个程序执行结果的问题
来源: 互联网 发布时间:2016-11-03
本文导语: 程序是:#include struct student { char name[10]; int age; }; int main() { FILE *fp; int i; struct student boy[2], *qq; if ((fp = fopen("file1.txt","r")) == NULL ...
程序是:#include
struct student {
char name[10];
int age;
};
int main()
{
FILE *fp;
int i;
struct student boy[2], *qq;
if ((fp = fopen("file1.txt","r")) == NULL )
{
printf("Can not open file, exit ...n");
return -1;
}
fseek(fp, sizeof(struct student), 0); //重定位流文件
fread(boy, sizeof(struct student), 1, fp);
printf("namettagen");
qq = boy;
for(i = 0; i name, qq->age);
}
fclose(fp);
return 0;
}
其中file1.txt是个空文件 ,gcc生成可执行文件后 执行打印结果是:[sn001@localhost test]$ gcc -o 84 8-4.c
[sn001@localhost test]$ ./84
name age
134518788
134518788 怎么来的?请指教
struct student {
char name[10];
int age;
};
int main()
{
FILE *fp;
int i;
struct student boy[2], *qq;
if ((fp = fopen("file1.txt","r")) == NULL )
{
printf("Can not open file, exit ...n");
return -1;
}
fseek(fp, sizeof(struct student), 0); //重定位流文件
fread(boy, sizeof(struct student), 1, fp);
printf("namettagen");
qq = boy;
for(i = 0; i name, qq->age);
}
fclose(fp);
return 0;
}
其中file1.txt是个空文件 ,gcc生成可执行文件后 执行打印结果是:[sn001@localhost test]$ gcc -o 84 8-4.c
[sn001@localhost test]$ ./84
name age
134518788
134518788 怎么来的?请指教
|
如果file1.txt是空文件的话,那么fseek()定位到文件之外了
|
在fopen之前,添加一个初始化语句试试
memset(boy, 0, sizeof(boy));
memset(boy, 0, sizeof(boy));
|
楼主没初始化呀
|
fread(boy, sizeof(struct student), 1, fp);
返回失败了,boy数据无效,而且你没有初始化boy。
返回失败了,boy数据无效,而且你没有初始化boy。