根据http://linux.die.net/man/3/sprintf和http://www.cplusplus.com/reference/cstdio/sprintf/ sprintf()和family返回成功写入的字符数.失败时,返回负值.我认为如果格式字符串格式错误可能会发生错误,因此负返回值可能表示malloc()错误以外的其他内容.是否errno设置为指示错误是什么?
C++推迟至C和C不要求或提到errno在描述sprintf()和家庭(虽然对于某些格式说明,这些功能被定义为调用mbrtowc(),其可设置EILSEQ在errno)
POSIX要求设置errno:
如果遇到输出错误,这些函数应返回负值并设置
errno为指示错误.
EILSEQ,EINVAL,EBADF,ENOMEM,EOVERFLOW明确提到:http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
当我有这样的问题时,我总是喜欢"试一试"方法.
char buffer[50];
int n, localerr = 0;
n = sprintf(buffer, "%s", "hello");
localerr = errno; // ensure printf doesn't mess with the result
printf("%d chars\nerrno: %d\nstrerror:%s\n", n, localerr, strerror(localerr));
> 5 chars
errno: 0
strerror: Success
n = sprintf(buffer, NULL, NULL);
localerr = errno;
printf("%d chars\nerrno: %d\nstrerror:%s\n", n, localerr, strerror(localerr));
> -1 chars
errno: 22
strerror: Invalid argument
Run Code Online (Sandbox Code Playgroud)
在linux上用gcc编译时看起来它已经设置好了.所以这是很好的数据,并且在它的手册页中errno确实提到printf()(同一系列sprintf())可能会改变errno(在底部的示例中).
| 归档时间: |
|
| 查看次数: |
5310 次 |
| 最近记录: |