You will want to look at Why is while ( !feof (file) ) always wrong?
Whenever you are reading data in a loop, you control the loop with the read function, e.g.
#define ROWS 100 /* if you need a constant, #define one (or more) */
#define COLS ROWS
...
/* you control the read loop with the read function itself
* you must protect your ROW bounds with the counter and
* protect your COL bounds with the field-width modifier.
*/
while (i < ROWS && fscanf (fp, "%99s", list[i]) == 1)
i++; /* increment counter */
Above you protect your ROWS
(rows) array bound by only adding a new word while your counter is less than the number of rows available. You protect your COLS
bound by using the field-width modifier to the "%s"
conversion specifier to ensure no more than 99
characters are read into your array (saving room for +1 -- the nul-terminating character).
(note: your words
array was superfluous. You can read directly into list
)
You now have all words read from the file stored in list. It doesn't matter whether there are one or more words on each line, you read a word-at-a-time and the "%s"
conversion specifier ignores leading whitespace (including '\n'
).
A short example that reads words from the file provided as the first argument to your program (or reads from stdin
by default if no argument was given) could be:
#include <stdio.h>
#define ROWS 100 /* if you need a constant, #define one (or more) */
#define COLS ROWS
int main (int argc, char **argv) {
char list[ROWS][COLS]; /* 2D array to hold strings (words) */
int i = 0; /* counter for strings */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
/* you control the read loop with the read function itself
* you must protect your ROW bounds with the counter and
* protect your COL bounds with the field-width modifier.
*/
while (i < ROWS && fscanf (fp, "%99s", list[i]) == 1)
i++; /* increment counter */
for (int j = 0; j < i; j++) /* output stored words */
printf ("list[%2d] : %s\n", j, list[j]);
if (fp != stdin) /* close file if not stdin */
fclose (fp);
}
Example Input File
Taking a file with multiple words on some lines and a single word on others:
$ cat dat/dictwrds20.txt
a
AAA
AAAS
aardvark Aarhus Aaron ABA
Ababa
aback
abacus abalone abandon abase
abash
abate abbas abbe
abbey
abbot
Abbott
Example Use/Output
The code above reads each word into your list
array without any problems:
$ ./bin/readlist dat/dictwrds20.txt
list[ 0] : a
list[ 1] : AAA
list[ 2] : AAAS
list[ 3] : aardvark
list[ 4] : Aarhus
list[ 5] : Aaron
list[ 6] : ABA
list[ 7] : Ababa
list[ 8] : aback
list[ 9] : abacus
list[10] : abalone
list[11] : abandon
list[12] : abase
list[13] : abash
list[14] : abate
list[15] : abbas
list[16] : abbe
list[17] : abbey
list[18] : abbot
list[19] : Abbott
Look things over and let me know if you have questions.