470,870 Members | 1,403 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,870 developers. It's quick & easy.

Reading from file and adding values to array

I am new to the C/C++

My Program:

int main(int argc, _TCHAR* argv[])

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
return 0;

//Config.txt Data


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[i] = 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
Nov 20 '07 #1
2 2146
112 100+

i think you didnt declare variable names i ?, and if you declare it and just you didnt post it within your code, you didnt increase it within loop

Best Regards
Nov 20 '07 #2
9,208 Expert Mod 8TB
There's a bigger bug here that just not declaring i.

There's this:
char datatext[1000];
sscanf (line, "%s", &datatext);
printf ("%s\n", datatext);
CheckPoint[i] = datatext;
Here CheckPoint[i] is assgined the address of the datatext array. As a result, every CheckPoint[i] will point to the same datatext array making the CheckPoint array elements to all be the same.

You need to a) find the length of the string in datatext, b) add 1 more for a null terminator, c) allocate memory for that length+1 and out that address in CheckPoint[i], d) copy datatext to the CheckPoint[i] array, e) write a loop at the nd of the program to delete all of the allocations made in the CheckPoint array.
Nov 20 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by SB | last post: by
8 posts views Thread by Yeow | last post: by
50 posts views Thread by Michael Mair | last post: by
6 posts views Thread by arne.muller | last post: by
11 posts views Thread by Freddy Coal | last post: by
3 posts views Thread by jordanbondo | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.