闡述 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+ 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告