Based on my reading of the C standard, if snprinf
reaches maxlen
while writing, it will return either a positive or negative value (it's not actually clear) that is equal in magnitude to the number of characters which failed to be written. The spec also says that the function will return a negative value for any error. So my question is: what does it return in the following two circumstances...
Maxlen > 0
, no characters are written before an error occurs and snprintf
bails
Maxlen > 0
, all characters are written, an error of some kind occurs and snprintf
bails
I realize that the last one, in particular, is unlikely. But I wanted to better understand the specification. It seems to me that snprintf's return makes it ambiguous whether you correctly wrote part of a string or not.
- Edit
Apparently this is not clear. Let me elaborate:
*> Which negative number doesn't matter. An error is an error, it doesn't
matter how many bytes were written before it occurred. That may be the practical case for most people. I saw that snprintf is supposed to return the number of excess characters, however, and I wanted to know if that value could be used. It seemed strange to me that the spec would go through the trouble of reporting something useful, only to leave it ambiguous as to whether it was really returning something irrelevant. Does that not make sense? I wanted to know if there was more to the convention that made it possible to determine if snprintf failed because it was given too much input.*
I get it now. I see that any error other than truncation is negative, success is 0 < R <= maxsize, truncation is 0 < maxsize < R. Thanks everyone who responded.