Writing a structure into a file

Discussion in 'C' started by mdzkhan, Jun 24, 2008.

  1. mdzkhan

    mdzkhan New Member

    Joined:
    Jun 24, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I am using the following code
    Code:
    typedef struct A {
    int x;
    int y;
    int  z;
    };
    
    int main(void) {
    
     struct A A;
     struct A B;
    FILE *fp;
    A.x = 80000;
    A.y = 40000;
    A.z = 12345;
    
    printf("%d %d %d\n", A.x, A.y, A.z);
    fp = fopen("file.txt", "wb");
    fwrite(&A, sizeof A, 3, fp);
    fclose(fp);
    fp = fopen("file.txt", "rb");
    fread(&B, sizeof B, 1, fp);
    fclose(fp);
    printf("%d %d %d\n", B.x, B.y, B.z);
    return 0;
    }
    
    
    But the file.txt is containing junk values when i open it . Please let me know what is wrong in my program.

    Thanks,
    Zaheer
     
    Last edited by a moderator: Jun 24, 2008
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,336
    Likes Received:
    377
    Trophy Points:
    83
    Because you are writing it in binary mode.
     
  3. Subrat_Mishra

    Subrat_Mishra New Member

    Joined:
    Jun 28, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Because you have assigned the value to int type variable beyond its range.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice