Tutorial :How can I get how many bytes sscanf_s read in its last operation?



Question:

I wrote up a quick memory reader class that emulates the same functions as fread and fscanf.

Basically, I used memcpy and increased an internal pointer to read the data like fread, but I have a fscanf_s call. I used sscanf_s, except that doesn't tell me how many bytes it read out of the data.

Is there a way to tell how many bytes sscanf_s read in the last operation in order to increase the internal pointer of the string reader? Thanks!

EDIT:

And example format I am reading is: |172|44|40|128|32|28|

fscanf reads that fine, so does sscanf. The only reason is that, if it were to be:

|0|0|0|0|0|0|

The length would be different. What I'm wondering is how fscanf knows where to put the file pointer, but sscanf doesn't.


Solution:1

Maybe I´m silly, but I´m going to try anyway. It seems from the comment threads that there's still some misconception. You need to know the amount of bytes. But the method returns only the amount of fields read, or EOF.

To get to the amount of bytes, either use something that you can easily count, or use a size specifier in the format string. Otherwise, you won't stand a chance finding out how many bytes are read, other then going over the fields one by one. Also, what you may mean is that

sscanf_s(source, "%d%d"...)   

will succeed on both inputs "123 456" and "10\t30", which has a different length. In these cases, there's no way to tell the size, unless you convert it back. So: use a fixed size field, or be left in oblivion....

Important note: remember that when using %c it's the only way to include the field separators (newline, tab and space) in the output. All others will skip the field boundaries, making it harder to find the right amount of bytes.

EDIT:
From "C++ The Complete Reference" I just read that:

%n   Receives an integer value equal to the nubmer of characters read so far

Isn't that precisely what you were after? Just add it in the format string. This is confirmed here, but I haven't tested it with sscanf_s.


Solution:2

With scanf and family, use %n in the format string. It won't read anything in, but it will cause the number of characters read so far (by this call) to be stored in the corresponding parameter (expects an int*).


Solution:3

From MSDN:

sscanf_s, _sscanf_s_l, swscanf_s, _swscanf_s_l    

Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »