Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C를 사용하여 파일에 구조 읽기/쓰기

<시간/>

fwrite() 및 fread()는 C에서 파일에 쓰는 데 사용됩니다.

fwrite() 구문

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

어디에

ptr - 쓸 요소의 배열에 대한 포인터

size - 쓸 각 요소의 크기(바이트)

nmemb - 바이트 크기의 요소 수

stream – 출력 스트림을 지정하는 FILE 객체에 대한 포인터

fread() 구문

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

어디에

ptr - size*nmemb 바이트의 최소 크기를 가진 메모리 블록에 대한 포인터입니다.

size - 읽을 각 요소의 크기(바이트)입니다.

nmemb - 각 요소의 크기가 바이트 크기인 요소의 수입니다.

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, "\nError to open the file\n");
      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 !\n");
   else
      printf("Error writing file !\n");
   fclose (of);
   FILE *inf;
   struct Student inp;
   inf = fopen ("c1.txt", "r");
   if (inf == NULL) {
      fprintf(stderr, "\nError to open the file\n");
      exit (1);
   }
   while(fread(&inp, sizeof(struct Student), 1, inf))
      printf ("roll_no = %d name = %s\n", inp.roll_no, inp.name);
   fclose (inf);
}

출력

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