-
I/O and Array Problems
Hello everyone. The problem I am having is that I am reading from a predefined text file with this type of stucture:
Code:
name id
name id
name id
name id
name id
What I am trying to do is to read all of the names into one array and all of the ids into another.
Code:
char* name[4];
int ids[4];
I need to use the method fgets(). I can successfully read the file, but am not sure of the correct way of putting them into the array. I was trying something like this, but to no avail:
Code:
i = 0;
while (fgets(line, 2048, pfile) != NULL)
{
printf("%s", line);
strcpy(stid[i], line);
i++;
}
From my results, it outputs everything perfectly to the console, but I can't figure out a way to put the data in arrays. Right here, I am just attempting to put the whole line into an array. If you can put me on the right track, I can split the data up later on my own. I just need help on the right way to write to arrays.
-
>char* name[4];
If you use this to store the name, you'd need to allocate space for each name using malloc(). For example, say you already had name stored in temp_name. Then:
Code:
name[i] = malloc(strlen(temp_name)+1); /* allocate space for string */
strcpy(name[i], temp_name);
Or you can make name an array of strings, and no malloc() would be needed, but the size of the strings would be limited to whatever size you declare:
Code:
char name[4][80];
strcpy(name[i], temp_name);
-
Perfect thank you. Didn't know that allocation was needed.
Thanks again.
-
>Perfect thank you. Didn't know that allocation was needed.
One other note. It's good practice to free the memory at the end of your program, or at the point where it's no longer needed:
Code:
for (i=0; i<num_names; i++)
{
free(name[i]);
}
-
Of course, if there are 5 items in your file, you probably should have
Code:
char name[5][80];
int ids[5];
Note that C arrays have the SIZE (number of elements in the array) in the brackets, and the index goes from 0..size-1, so 5 allows you to use 5 elements, which are numbered 0, 1, 2, 3 and 4.
--
Mats