By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,915 Members | 1,345 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,915 IT Pros & Developers. It's quick & easy.

Reading from file and adding values to array

P: 2
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
Share this Question
Share on Google+
2 Replies

P: 112

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

Expert Mod 5K+
P: 9,197
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.