Question

I am reading text file (.txt) and getting values inside of it.

Here is my code:

// Definitions.
FILE* file;
date t1, calc[99999];
int index = 0, counter = 0, i;
char info[100];
char *newInfo[9999];

while(!feof(file)){
                fscanf(file, "%s %d %d %d\n", info, &t1.day, &t1.month, &t1.year);
                newInfo[index] = info;
                calc[index].day = t1.day;
                calc[index].month = t1.month;
                calc[index].year = t1.year;
                printf("read: %s %d %d %d\n", info, t1.day, t1.month, t1.year);
                index++;
                counter++;
        }

The result is:

line_1 01 01 2011
line_2 02 02 2012
line_3 03 03 2013

It is okay so far but when I try to print them out of while loop, it always prints last value which is line_3.

for(i = 0; i < counter; i++)
printf("%s %d %d %d\n", newInfo[i], calc[i].day, calc[i].month, calc[i].year);

Result is:

line_3 01 01 2011
line_3 02 02 2012
line_3 03 03 2013

It is supposed to print result as I expected (which I showed above).

I am making assignment at newInfo[index] = info; line and increasing index variable. But it still shows me only latest text.

Any help would be much appreciated.

Was it helpful?

Solution 2

Strings in C are not first-class objects -- they're just a special case of arrays, which themselves are just a special case of pointers. One of the consquences of this is that operations such as assignment don't work as you'd expect. The line

newInfo[index] = info;

isn't copying the string "info", it's copying the underlying pointer. In order to copy a string, you need to use "strcpy()" (if you've already allocated space for the string), or "strdup()" if you haven't (and then you need to remember to free the memory allocated). In your code, you would replace the above line with

newInfo[index] = strdup(info);

OTHER TIPS

newinfo is an array of ptrs. Each of those pointers is set to point to info. info is going to hold the last thing it read so, consequently every pointer in newinfo is going to point to the last thing read.

Well, you save the info into the same array each time, copying the pointer (start of array) represented by info to NewInfo[index], which doesn't help.

You have to allocate space for the string to go in, and assign that to NewInfo[index]. Simplest, if your system has it, is:

NewInfo[index] = strdup(info);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top