File I/O with Binary Data in C

 File I/O with Binary Data in C


C provides file I/O operations for reading and writing binary data. This is useful when working with files that store structured data or when you need to perform low-level data manipulation.



#include <stdio.h>


struct Person {

    char name[50];

    int age;

    float height;

};


int main() {

    struct Person person = {"John", 25, 175.5};


    FILE* file = fopen("data.bin", "wb");

    if (file == NULL) {

        printf("File could not be opened.\n");

        return 1;

    }


    fwrite(&person, sizeof(struct Person), 1, file);

    fclose(file);


    file = fopen("data.bin", "rb");

    if (file == NULL) {

        printf("File could not be opened.\n");

        return 1;

    }


    struct Person readPerson;

    fread(&readPerson, sizeof(struct Person), 1, file);

    printf("Name: %s\n", readPerson.name);

    printf("Age: %d\n", readPerson.age);

    printf("Height: %.2f\n", readPerson.height);


    fclose

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...