sprintf()负返回值和errno

use*_*450 12 c printf errno

根据http://linux.die.net/man/3/sprintfhttp://www.cplusplus.com/reference/cstdio/sprintf/ sprintf()和family返回成功写入的字符数.失败时,返回负值.我认为如果格式字符串格式错误可能会发生错误,因此负返回值可能表示malloc()错误以外的其他内容.是否errno设置为指示错误是什么?

Cub*_*bbi 9

C++推迟至C和C不要求或提到errno在描述sprintf()和家庭(虽然对于某些格式说明,这些功能被定义为调用mbrtowc(),其可设置EILSEQerrno)

POSIX要求设置errno:

如果遇到输出错误,这些函数应返回负值并设置errno为指示错误.

EILSEQ,EINVAL,EBADF,ENOMEM,EOVERFLOW明确提到:http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html

  • @StoneThrow 您使用的操作系统决定了这一点。如果是 Unix(包括 MacOS 和 Linux),则适用 POSIX。如果是 Windows,则取决于其 libc 作者的心血来潮。 (2认同)

Mik*_*ike 5

当我有这样的问题时,我总是喜欢"试一试"方法.

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(在底部的示例中).

  • 请注意,“试用”方法依赖于符合标准的实现,并且该标准不允许不同的行为有空间。有时这种方法会误导你...... (2认同)