reading lines with fscanf
Not.
But I, although it was a good idea, because ...
Not.
Reading lines are executed using the fgets() function ( read a funny guide ):
char buf[LINE_MAX]; while (fgets(buf, sizeof buf, file) != NULL) {
You can then parse it using sscanf() (not preferred) or reasonable functions like strchr() and strtok_r() (preferred). Also, do not (h) assume that the return value of scanf() ( docs ) is not EOF , but the number of objects successfully read. So a lazy approach for parsing a string can be:
if (sscanf(buf, "%s %s %s %s %s %s %s %s %s", s1, s2, ...) < 9) { // there weren't 9 items to convert, so try to read 8 of them only }
Also note that you are better off using the length limit with the %s conversion specifier to avoid buffer overflow errors, for example:
char s1[100]; sscanf(buf, "%99s", s1);
Similarly, you should not use the address operator & when scanning (c) a string - the char array already decays to char * , and this is exactly what the conversion specifier %s expects - type &s1 is equal to char (*)[N] if s1 - an array of N char - and the type of mismatch makes scanf() invoke undefined behavior.
user529758
source share