1

I want to read a file with 3 lines:

The first one with strings, second with a number and the third with strings again.

Example:

Line 1: bird toy book computer water

Line 2: 2

Line 3: toy water

I have this code, that reads a file, word by word storing them in the word array, and then putting the word into the words 2d array.

char words [5][50];
char word [50];
int i,j;
j = 0;

while( (fscanf(file, "%s", word))!=EOF ){
    for(i = 0; i<50; i++){
        if(word[i] != NULL){
            words[j][i] = word[i];
        } else{
            break;
        }
    }
    j++;

}

it's working, but it reads all the lines, i want a way to just do this process for the first line, and then store the second line into a int variable and the third line into another 2d array.

Alex Ferreira
  • 23
  • 1
  • 5

1 Answers1

7

Read more about fscanf. It is not suitable to read line by line.

Consider instead reading every line with fgets or even better (on POSIX) with getline (see this), then parse each line perhaps with sscanf. Its return value (the count of scanned items given from sscanf etc...) could be useful to test (and you might also want to use %n in the scan control format string; as Jonathan Leffler commented, read also about %ms assignment-allocation modifier, at least on POSIX systems, see Linux sscanf(3)).

BTW, hard-coding limits like 50 for your word length is bad taste (and not robust). Consider perhaps using more systematically C dynamic memory allocation (using malloc, free and friends) and pointers, perhaps using sometimes flexible array members in some of your struct-s

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    If you've got support for POSIX [`sscanf()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html), the `m` 'assignment-allocation' modifier is useful in `%ms`. It dynamically allocates the space needed to hold the string that's read — but the `sscanf()` argument is a `char **`, not a `char *`. Not all Unix-like systems support it though — specifically, macOS Sierra 10.12.5 does not, nor do the prior Mac OS X versions. – Jonathan Leffler Jul 01 '17 at 16:08