使用 C 读取/写入文件中的结构


fwrite() 与 fread() 用于在 C 中写入文件。

fwrite() 语法

fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

其中

ptr - 要写入的元素数组的指针

size - 要写入的每个元素的字节大小

nmemb - 元素数,每个元素的大小为 bytes

stream – 指向指定输出流的 FILE 对象的指针

fread() 语法

fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

其中

ptr - 指向大小至少为 size*nmemb 字节的内存块的指针。

size - 要读取的每个元素的字节大小。

nmemb - 元素数,每个元素的大小为 bytes。

stream - 指向指定输入流的 FILE 对象的指针。

算法

Begin
   Create a structure Student to declare variables.
   Open file to write.
   Check if any error occurs in file opening.
   Initialize the variables with data.
   If file open successfully, write struct using write method.
      Close the file for writing.
   Open the file to read.
   Check if any error occurs in file opening.
   If file open successfully, read the file using read method.
      Close the file for reading.
   Check if any error occurs.
   Print the data.
End.

这是一个在 C 中读/写结构的示例

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
   int roll_no;
   char name[20];
};
int main () {
   FILE *of;
   of= fopen ("c1.txt", "w");
   if (of == NULL) {
      fprintf(stderr, "
Error to open the file
");       exit (1);    }    struct Student inp1 = {1, "Ram"};    struct Student inp2 = {2, "Shyam"};    fwrite (&inp1, sizeof(struct Student), 1, of);    fwrite (&inp2, sizeof(struct Student), 1, of);    if(fwrite != 0)       printf("Contents to file written successfully !
");    else       printf("Error writing file !
");    fclose (of);    FILE *inf;    struct Student inp;    inf = fopen ("c1.txt", "r");    if (inf == NULL) {       fprintf(stderr, "
Error to open the file
");       exit (1);    }    while(fread(&inp, sizeof(struct Student), 1, inf))       printf ("roll_no = %d name = %s
", inp.roll_no, inp.name);    fclose (inf); }

输出

Contents to file written successfully !
roll_no = 1 name = Ram
roll_no = 2 name = Shyam

更新于: 30-Jul-2019

1.1 万次浏览

开启您的 职业

完成课程以获得认证

开始学习
广告