首页 新闻 会员 周边

文件读写结果为何为笑脸

0
悬赏园豆:10 [已解决问题] 解决于 2011-03-19 22:55

为什么下面的程序读文件却只得到一个笑脸?请大家帮忙

#include <stdlib.h>
#include
<stdio.h>
#include
<string.h>

struct student
{
int number;
char name[20];
int age;
char project[50];
}stu[
2];

void main()
{
FILE
*fp;
int i;
int len;
struct student *buffer;
char *result = NULL;

printf(
"Please input the number,name,age and project for 2 sutdents:\n");
for (i=0; i<=1; i++)
{
scanf(
"%d,%s,%d,%s", &stu[i].number, stu[i].name, &stu[i].age, stu[i].project);}



//建立文件students,将刚才输入的2个学生的信息保存进该文件中

if ( ( fp=fopen("students","wb") )==NULL )
{
printf(
"Can not open the students file.\n");
}

for (i=0; i<=1; i++)
{
fwrite(
&stu[i], sizeof(struct student), 1, fp);
}

fclose(fp);

//打开刚才建立的students文件,读取并显示其中的内容
if ( (fp=fopen("students","r"))==NULL )
{
P(
"Can not open the students file.\n");
exit(
0);
}

fseek(fp,
0, SEEK_END);

len
=ftell(fp); //获取students文件的长度,赋给len.

fseek(fp,
0,SEEK_SET);

buffer
=(student *)malloc(len);
char * line = (char *)buffer;

int temp;
while(fgets(line,len,fp) != NULL)
{
result
= strtok(line,",");
for(temp=0; temp< 4; temp++)
{
while(result != NULL)
{
fputs(result,stdout);
fputs(
"\t",stdout);
result
= strtok(NULL, ",");
}
}
}
}
ttssrs的主页 ttssrs | 初学一级 | 园豆:82
提问于:2011-03-18 22:20
< >
分享
最佳答案
0

int number;
char name[20];

这两个顺序换过来。下面scanf也换过来。

fwrite有这么个毛病,不知道什么原因。

建议用fprintf

代码如下:

View Code
#include <stdlib.h>
#include
<stdio.h>
#include
<string.h>
struct student{
char name[20];//////////////////
int number;
int age;
char project[50];
}stu[
2];
void main()
{
FILE
*fp;
int i;
int len;
struct student *buffer;
char *result = NULL;
printf(
"Please input the name,number,age and project for 2 sutdents:\n");
for (i=0; i<=1; i++){
scanf(
"%s,%d,%d,%s", stu[i].name, &stu[i].number, &stu[i].age, stu[i].project);
}
//建立文件students,将刚才输入的2个学生的信息保存进该文件中
if ((fp=fopen("students","wb"))==NULL )
{
printf(
"Can not open the students file.\n");
}
for (i=0; i<=1; i++)
{
fwrite(
&stu[i], sizeof(struct student), 1, fp);
}
fclose(fp);
//打开刚才建立的students文件,读取并显示其中的内容
if ( (fp=fopen("students","r"))==NULL )
{
printf(
"Can not open the students file.\n");
exit(
0);
}
fseek(fp,
0, SEEK_END);
len
=ftell(fp); //获取students文件的长度,赋给len.
fseek(fp,0,SEEK_SET);
buffer
=(student *)malloc(len);
char * line = (char *)buffer;
int temp;
while(fgets(line,sizeof(student)+1,fp) != NULL)/////////////////len+1
{
result
= strtok(line,",");
for(temp=0; temp< 4; temp++)
{
while(result != NULL)
{
fputs(result,stdout);
fputs(
"\t",stdout);
result
= strtok(NULL, ",");
}

}
fputs(
"\n",stdout); ////////////////////////
}
}
收获园豆:10
Rusty's code | 菜鸟二级 |园豆:410 | 2011-03-19 21:45
或者看这里
http://topic.csdn.net/u/20100415/11/1313f123-a607-4349-87ed-c5fcd0485cc4.html
Rusty's code | 园豆:410 (菜鸟二级) | 2011-03-19 22:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册