how can I save struct in file … C lang

前端 未结 6 847
悲&欢浪女
悲&欢浪女 2021-01-02 18:23

I\'d like to save a struct in a file. I\'d like to realize a function which makes this work. I tried this code but it didn\'t work.

struct utilisateur   //         


        
6条回答
  •  半阙折子戏
    2021-01-02 18:53

    Michael S is right; using fwrite with a struct is wildly nonportable. But let's assume you don't care about that and you want something easy to write that will work.

    The problem in your code is that you've broken the Golden Rule of sizeof: never use sizeof with a type name. Instead you should use sizeof with an lvalue, and almost always with the dereference of another argument. Thus

    Tutilis = malloc (sizeof (*Tutilis));
      ...
    fwrite(Tutilis, sizeof (*Tutilis), 1, f);
    

    If you follow this recipe it's much harder to get the size wrong.

提交回复
热议问题