简体   繁体   中英

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

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.

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* ).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM