Search code examples
cfwrite

How do I use struct and arrays to fill a file using fwrite function in C?


I want to create a program that fills a file with properties of 5 students ( matricule , firstname , lastname ) using fwrite(), i tried to solve that using struct with arrays as shown bellow :

#include<stdio.h>
int main(){

    struct Student
    {
        char* matricule;
        char* nom ;
        char* prenom;
    };

    Student student[4];

    student[0].matricule = "m001";
    student[0].nom = "Boussaha";
    student[0].prenom = "Borhanedine";

    student[1].matricule = "m002";
    student[1].nom = "Toaba";
    student[1].prenom = "Anes";

    student[2].matricule = "m003";
    student[2].nom = "Laamari";
    student[2].prenom = "Loqmane";

    student[3].matricule = "m004";
    student[3].nom = "Dellachi";
    student[3].prenom = "Amir";

    student[4].matricule = "m005";
    student[4].nom = "Zenfour";
    student[4].prenom = "Abdelmouiz";

    
    FILE *f;
    f = fopen("list.data" , "wb");

    for (int i = 0; i < 5; i++)
    {
        fwrite(student[i].matricule , sizeof(student[i].matricule) , 5 , f);
        fwrite(student[i].nom , sizeof(student[i].nom) , 5 , f);
        fwrite(student[i].prenom , sizeof(student[i].prenom) , 5 , f);
    }
}

I guess and hope nothing is wrong in the code.

When I debug the program, the file gets created but I find it empty. I am wondering why it is empty when I was expecting the file to be filled with the properties of each student?


Solution

    • Student student[4]; allocates enough room for 4 elements. This means student[0] through student[3] is valid, but student[4] is not valid. Accessing student[4] effectively makes you program behave unpredictably. Set it to Student student[5].

    • f = fopen("list.data" , "wb"); is okay, but did you check for errors? if(f==0) then an error has occurred. Better safe than sorry.

    • fwrite(student[i].XYZ , sizeof(student[i].XYZ) , 5 , f); is very wrong. I'm not sure if you're new to C but I can tell you that sizeof does not do what you think it does. And I bet you don't seem to know why that 5 is there either. Replace sizeof with strlen, and replace 5 with 1.