Curious Guy 007
Curious Guy 007

Reputation: 571

sscanf reading multiple characters

I am trying to read a list of interfaces given in a config file.

 char readList[3];

 memset(readList,'\0',sizeof(readList));

 fgets(linebuf, sizeof(linebuf),fp); //I get the file pointer(fp) without any error

 sscanf(linebuf, "List %s, %s, %s \n",
               &readList[0],
               &readList[1],
               &readList[2]);

Suppose the line the config file is something like this list value1 value2 value3

I am not able to read this. Can someone please tell me the correct syntax for doing this. What am I doing wrong here.

Upvotes: 0

Views: 2159

Answers (2)

ajay
ajay

Reputation: 9680

The %s conversion specifier in the format string reads a sequence of non-whitespace characters and stores in buffer pointed to by the corresponding argument passed to sscanf. The buffer must be large enough to store the input string plus the terminating null byte which is added automatically by sscanf else it is undefined behaviour.

char readList[3];

The above statement defines readList to be an array of 3 characters. What you need is an array of characters arrays large enough to store the strings written by sscanf. Also the format string "List %s, %s, %s \n" in your sscanf call means that it must exactly match "List" and two commas ' in that order in the string linebuf else sscanf will fail due to matching failure. Make sure that you string linebuf is formatted accordingly else here is what I suggest. Also, you must guard against sscanf overrunning the buffer it writes into by specifying the maximum field width else it will cause undefined behaviour. The maximum field width should be one less than the buffer size to accommodate the terminating null byte.

// assuming the max length of a string in linebuf is 40
// +1 for the terminating null byte which is added by sscanf 

char readList[3][40+1];  
fgets(linebuf, sizeof linebuf, fp);

// "%40s" means that sscanf will write at most 40 chars
// in the buffer and then append the null byte at the end.

sscanf(linebuf, 
       "%40s%40s%40s",
       readList[0],
       readList[1],
       readList[2]);

Upvotes: 1

Gassa
Gassa

Reputation: 8846

Your char readlist[3] is an array of three chars. What you need however is an array of three strings, like char readlist[3][MUCH]. Then, reading them like

sscanf(linebuf, "list %s %s %s",
                readList[0],
                readList[1],
                readList[2]);

will perhaps succeed. Note that the alphabetic strings in scanf need to match character-by-character (hence list, not List), and any whitespace in the format string is a signal to skip all whitespace in the string up to the next non-whitespace character. Also note the absence of & in readList arguments since they are already pointers.

Upvotes: 1

Related Questions