当前位置:编程学习 > C/C++ >>

C语言问题如下:

我定义了这么一个结构体:
typedef struct STUDENT
{
 char id[10];
 char name[20];
 char score[4];
}Stu;

我想用fread函数正确读取如图所示内容,我是这么写的
 fgets(ch,500,fp);

 for(i=0;i<6;i++)
 {
 
  fread(&stu[i],sizeof(stu[i]),1,fp);
  printf("%s      %s    %s\n",stu[i].id,stu[i].name,stu[i].score);
 
  fgetc(fp);
 }
但失败了。

请问该怎么写读取这么这段的代码?



答案:Hello,我是“百度知道”被你忽悠过来的(找了半天才找到你的问题),看了你写的程序,我觉得应该是这个原因让你出错!

你要读取的文档的类型为“txt”文档,fread()只能读取二进制格式的文档,所以说,你这文档,fread()不能读取【刚刚翻书查的,你可以问问你们老师,我也不是很确定】

所以说,要解决你这个错误,首先,你要建立一个二进制文件,就是利用书上的fopen(“stu_list”,"wb+")来创建,创建完了以后,你再从控制台输入 学生信息 (就是你txt上的内容)作为文件内容,最后,你再用fread()函数来读取你存储的信息!!

就是这么简单!!

下面是我写的,仅供参考:

#include<stdio.h>
#define SIZE 4
struct student_type
{
 char name[10];//这边要注意,我把所有的变量类型都设置为char型,为了你用“txt”形式打开文件时

 char id[10];//存储的信息显示出错!!(*^__^*) 
 char age[10];
 char addr[10];
}stud[SIZE];
void save()
{
 FILE *fp;
 int i=0;
 if((fp=fopen("stu_list","wb+"))==NULL)
 {
  printf("cannot open the file\n");
  return;
 }
 for(i=0;i<SIZE;i++)
  fwrite(&stud[i],sizeof(struct student_type),1,fp);
 fclose(fp);
 printf("task over\n");
}
void main()
{
 int i;

struct student_type stu[SIZE];
 for(i=0;i<SIZE;i++)
  scanf("%s%s%s%s",&stud[i].name,&stud[i].id,&stud[i].age,&stud[i].addr);
 save();

//读取信息

 FILE *fp;
 if((fp=fopen("stu_list","wr"))==NULL)
 {
  printf("cannot open the file\n");
  return;
 }
 for(i=0;i<SIZE;i++)
  fread(&stu[i],sizeof(struct student_type),1,fp);

 printf("%s %s %s%s\n",&stud[i].name,&stud[i].id,&stud[i].age,&stud[i].addr);
 fclose(fp);
}

 

fp得指向那个数据文件啊

先定义FILE *fp;

                if((fp=fopen("data.txt","r")==NULL))

                 {printf"cannot open";

                   exit;}

你定义的Stu,后面用的是stu;..........反正错误多多

你重新写吧

          

i = 0;
fgets(str,500,fp); // str :字符数组
while(fscanf("%s%s%f",stu[i].id,stu[i].name,&stu[i].score[0]) == 3) {
    printf("%s\t%s\t%s\n",stu[i].id,stu[i].name,stu[i].score[0]);
    ++i;
}
注意,请必须用fread函数。

上一个:菜鸟入门学习c语言
下一个:如何速成学习C语言

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,