为什么下面的程序读文件却只得到一个笑脸?请大家帮忙
#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, ",");
}
}
}
}
int number;
char name[20];
这两个顺序换过来。下面scanf也换过来。
fwrite有这么个毛病,不知道什么原因。
建议用fprintf
代码如下:
#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); ////////////////////////
}
}