'How to detect end of 'array of strings'? (in c)

If you are confused with "Array of strings" it is basically char arr[10][10];. I'm trying to type out an array of strings using 'for' loop, and the length of that array of strings is unknown (it's variable). How do I write a 'for' loop that would know where is the end of that array of strings and stop writing? (btw if you're curious as to what I'm needing, it is for a system that reads strings from a text file line by line and puts them in an array of strings) I can however detect EOF, so right now I'm using a for loop that puts lines in an array of strings, and immediately prints it... here it is:

fp = fopen ("file.txt","r");
for(i=0;!feof(fp);i++)
{
    fgets(array[i],20,fp);
    printf("\n%s",array[i]);
}
fclose(fp)


Solution 1:[1]

Just check the return value of fgets() and keep a counter, when you get a NULL pointer, there is (probably) nothing more to read from the file.

   char array[10][10];
   FILE *fp = fopen ("file.txt","r");
   size_t max_size = sizeof(array) / sizeof(array[0]);
   size_t length = 0;


    while (length < max_size && fgets(array[length], sizeof(array[0]), fp) != NULL)
    {
        length++;
    }

   printf("%zu\n", length);
   fclose(fp);

But note that you might go out of bounds if it happens there are more than 10 lines in the file. You should also check that length is within the bounds of the array.

fgets() will also set errno to indicate the error, if you are on a POSIX-like system.

Also, see Why is “while ( !feof (file) )” always wrong and Why it's bad to use feof() to control a loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1