1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Problem while populating structure

Discussion in 'C' started by rajanandhini, Jul 31, 2008.

  1. rajanandhini

    rajanandhini New Member

    Joined:
    Jun 12, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    I need to populate a structure with the values from a string.I tried using strncpy but it did not work. Please let me know if any more details are required. Please find the below code and help me.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    struct file
    {
    const char filename[2];
    const char data[12];
    const char data2[4];
    };
    struct file file1;
    
    void main()
    {
    char a[25];
    FILE *fp;
    
    strcpy(a,"te this is test abcd");
    strncpy(file1.filename,a,sizeof(file1));
    
    fp=fopen(file1.filename,"w");
    fwrite(file1.data,12,1,fp);
    }
    
    I need to populate the structure as:
    filename:te
    data:this is test
    data2:abcd

    Please help me
    Thanks,
    nan
     
    Last edited by a moderator: Jul 31, 2008
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    You need to allow space for the terminating NULLs. In C the string "te" is represented by the THREE characters 't', 'e' and 0. Most string functions depend on this, so while you CAN store 't' and 'e' in a char[2] you really need to know what you are doing.

    Secondly you need to know what const means. It means something is a constant and can't be changed. So don't make stuff const that you want to change.

    sizeof(file1) will give you the size of the structure, not the size of one of its elements.

    ALWAYS clean up resources you allocate. This means you need an fclose somewhere.
     

Share This Page