[c언어] 파일에서 구조체 데이터 읽고 쓰는 방법

이번 포스트에서는 C 언어에서 파일에서 구조체 데이터를 읽고 쓰는 방법에 대해 알아보겠습니다.

구조체(Struct) 정의하기

먼저, 파일에서 읽고 쓸 구조체를 정의하는 것으로 시작합니다. 아래는 학생 정보를 나타내는 구조체의 예시입니다.

typedef struct {
    char name[50];
    int age;
    float gpa;
} Student;

파일에 데이터 쓰기

이제 구조체 데이터를 파일에 쓰는 방법을 알아봅시다. fwrite 함수를 사용하여 구조체 데이터를 파일에 씁니다.

#include <stdio.h>

int main() {
    FILE *file;
    Student student = {"John", 20, 3.5};
    
    file = fopen("students.dat", "wb");
    fwrite(&student, sizeof(Student), 1, file);
    fclose(file);
    
    return 0;
}

위 코드에서, fwrite 함수는 구조체 studentstudents.dat 파일에 이진 모드로 씁니다.

파일에서 데이터 읽기

이제 파일에서 구조체 데이터를 읽는 방법을 살펴봅시다. fread 함수를 사용하여 파일에서 구조체 데이터를 읽어옵니다.

#include <stdio.h>

int main() {
    FILE *file;
    Student student;

    file = fopen("students.dat", "rb");
    fread(&student, sizeof(Student), 1, file);
    
    printf("Name: %s, Age: %d, GPA: %.2f\n", student.name, student.age, student.gpa);
    
    fclose(file);

    return 0;
}

위 코드에서, fread 함수는 students.dat 파일에서 구조체를 읽어 student 변수에 저장합니다. 그 후에는 printf 함수를 사용하여 읽은 데이터를 출력합니다.

이제 파일에서 구조체 데이터를 읽고 쓰는 방법을 알게 되었습니다. 파일 처리와 구조체를 함께 사용하여 강력하고 유연한 데이터 저장 및 관리 시스템을 만들 수 있습니다.

참고 문헌: