Reading from file and adding values to array

Discussion in 'C' started by srinivas@e-spec.net, Nov 20, 2007.

  1. srinivas@e-spec.net

    srinivas@e-spec.net New Member

    Joined:
    Nov 12, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Reading from file and adding values to array
    --------------------------------------------------------------------------------

    I am new to the C/C++

    My Program:

    Code:
    int main(int argc, _TCHAR* argv[])
    {
    //Declarations
    
    FILE *fp;
    char line[1000];
    char *CheckPoint[3000];
    
    //Opening a file and reading
    
    fp = fopen("C:\\config.txt","rt");
    while(fgets(line, 1000, fp) != NULL)
    {
    char datatext[1000];
    sscanf (line, "%s", &datatext);
    printf ("%s\n", datatext);
    CheckPoint[i] = datatext;
    }
    
    //Closing File
    fclose(fp);
    return 0;
    }
    
    
    //Config.txt Data

    10
    20
    30
    40


    My Question:

    I am able to read the data from the file from the above loop of reading the file
    but when i add it to the array the value incrementing the array and assiging it, the values gets changed

    first time from the txt file i get 10 and i add to CheckPoint = datatext; where initially i =0, the next loop when the value for the datatext = 20 the initial value get to 20 and also inserts 20 in the second place

    Where am i going wrong

    Please help me
     
    Last edited by a moderator: Nov 20, 2007
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    I don't see the i variable being declared as well as incremented and so I think your data is getting changed.
     
  3. Salem

    Salem New Member

    Joined:
    Nov 15, 2007
    Messages:
    133
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Please don't PM me for 1:1 support.
    > CheckPoint = datatext;
    This is only a pointer, so when datatext is changed next time around the loop, then all the pointers to it will also appear to change as well.

    Make CheckPoint a true 2D array of chars, and use strcpy() to copy datatext.

    Or you might consider http://www.hmug.org/man/3/strdup.php, but that would not be a portable solution (although strdup is very easy to write yourself).
     
  4. srinivas@e-spec.net

    srinivas@e-spec.net New Member

    Joined:
    Nov 12, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thank You Shabbir & Salem

    Sorry to post a wrong code for not giving the initilizing the i variable as i have declared in my program

    strdup worked out

    Thank you once again
     

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