阐述 C 语言中用于文件操作的 fread() 和 fwrite() 函数


问题

编写一个 C 语言程序,用文件保存 5 个学生的详细信息,然后再使用 fread() 和 fwrite() 打印这些信息

解决方案

fread() 函数每次读取整个记录。

语法

fread( & structure variable, size of (structure variable), no of records, file pointer);

示例

struct emp{
   int eno;
   char ename [30];
   float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);

fwrite() 函数每次写入整个记录。

语法

fwrite( & structure variable , size of structure variable, no of records, file pointer);

示例

struct emp{
   int eno:
   char ename [30];
   float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);

程序

#include<stdio.h>
struct student{
   int sno;
   char sname [30];
   float marks;
   char temp;
};
main ( ){
   struct student s[60];
   int i;
   FILE *fp;
   fp = fopen ("student1.txt", "w");
   for (i=0; i<2; i++){
      printf ("enter details of student %d
", i+1);       printf("student number:");       scanf("%d",&s[i].sno);       scanf("%c",&s[i].temp);       printf("student name:");       gets(s[i].sname);       printf("student marks:");       scanf("%f",&s[i].marks);       fwrite(&s[i], sizeof(s[i]),1,fp);    }    fclose (fp);    fp = fopen ("student1.txt", "r");    for (i=0; i<2; i++){       printf ("details of student %d are
", i+1);       fread (&s[i], sizeof (s[i]) ,1,fp);       printf("student number = %d
", s[i]. sno);       printf("student name = %s
", s[i]. sname);       printf("marks = %f
", s[i]. marks);    }    fclose(fp);    getch( ); }

输出

enter details of student 1
student number:1
student name:pinky
student marks:56
enter details of student 2
student number:2
student name:rosy
student marks:87
details of student 1 are
student number = 1
student name = pinky
marks = 56.000000
details of student 2 are
student number = 2
student name = rosy
marks = 87.000000

更新日期:2021 年 3 月 6 日

19K+ 浏览

开启你的 职业生涯

完成课程,获得认证

开始学习
广告