Reading lines using fscanf

Hi, I have a file that contains the following lines:

wwa weweweof ewewe wdw: 1 11 ms <1 ms <1 ms 174.78.134.1 2 11 ms <1 ms <1 ms 174.78.134.1 3 5 ms <1 ms <1 ms x58trxd00.abcd.edu.com [143.71.290.42] 4 11 ms <1 ms <1 ms 174.78.134.1 

I use

  if(linecount == 8) while( fscanf(fp, "%d %s %s %s %s %s %s",&a1,&a2,&a3,&a4,&a5,&a6,&a7,&a8) != EOF ){ printf("%s",ch); } else if (linecount == 9){ while( fscanf(fp, "%d %s %s %s %s %s %s %s",&a1,&a2,&a3,&a4,&a5,&a6,&a7,&a8,&a9) != EOF ){ printf("%s",ch); } } 

how to check if lines in a file contain 8 or 9 elements so that I can execute the above else-if statements accordingly?

+4
source share
4 answers

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) { // process line here } 

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.

+10
source

Use fgets to get the row, and then run one sscanf to check for 9 elements, and if that fails, use sscanf again to check the row with 8 elements.

If the format of the string is equal to one additional element, then remember that the scanf family of functions returns the number of successfully scanned elements. Therefore, it can be quite simple to call sscanf once and check if it returns 8 or 9 .

+2
source

You should use the fgets() function because your swag value in your array is currently set to null .

0
source

and don't use & with data types of string type (char) with scanf

 scanf("%s",name); //use it without "&" sign 

Cause:

The "string" in C is the address of the character buffer. You want scanf to fill memory in the buffer pointed to by the variable.

In contrast, int is a block of memory, not an address. In order for scanf to fill this memory, you need to pass its address.

0
source

Source: https://habr.com/ru/post/1495694/


All Articles