I have a text file with up to 100 IP addresses, 1 per line. I need to read each address, as a string, into an array called "list". First, I'm assuming that "list" will need to be a two-dimensional char array. Each IP address is 11 characters in length, 12 if you include '\0', so I declared list as follows:
char list[100][12];
Next, I attempt to use fgets to read the stream:
for (i = 0; i < 100; i++)
{
if (feof(stream))
break;
for (j = 0; j < 12; j++)
fgets(&list[i][j], 12, stream);
count++;
}
To check to see if the strings were read properly, I attempt to output them:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 11; j++)
printf("%c", list[i][j]);
printf("\n");
}
After running the program, it's clear something is wrong. Being a beginner, I'm not sure what, but I'm guessing I'm reading the file wrong. There are no errors. It compiles, but prints a strange address on two lines.
Edit:
I replaced the fgets code with this:
for (i = 0; i < 100; i++)
{
if (feof(stream))
break;
fgets(list[i], 12, stream);
count++;
}
It now prints five strings, but they are "random" characters from memory.
You may be reading the first 12 characters in the first call the fgets, then the second call will catch the newline, then the third call gets the next line.
Try using fgets with a 15 character limit, and expanding your buffer.