Home / Programs / Write a C program to write all the members of an array of structures to a file using fwrite(). Read the array from the file and display on the screen.
🚀 Programming Example

Write a C program to write all the members of an array of structures to a file using fwrite(). Read the array from the file and display on the screen.

👁 10,269 Views
💻 Practical Program
📘 Step Learning
Write a C program to write all the members of an array of structures to a file using fwrite(). Read the array from the file and display on the screen.

💻 Program Code

#include <stdio.h>
struct student
{
   char name[50];
   int height;
};
int main(){
    struct student stud1[5], stud2[5];   
    FILE *fptr;
    int i;

    fptr = fopen("file.txt","wb");
    for(i = 0; i < 5; ++i)
    {
        fflush(stdin);
        printf("Enter name: ");
        gets(stud1[i].name);

        printf("Enter height: "); 
        scanf("%d", &stud1[i].height); 
    }

    fwrite(stud1, sizeof(stud1), 1, fptr);
    fclose(fptr);

    fptr = fopen("file.txt", "rb");
    fread(stud2, sizeof(stud2), 1, fptr);
    for(i = 0; i < 5; ++i)
    {
        printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
    }
    fclose(fptr);
}
                        

🖥 Program Output

See Your File Directory
                            

📘 Explanation

Write a C program to write all the members of an array of structures to a file using fwrite(). Read the array from the file and display on the screen.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.