2013-02-08 100 views

回答

9

C++推遲至C和C不要求或在sprintf()和家人的描述提errno(雖然對於某些格式說明,這些功能被定義調用mbrtowc(),其可以設置EILSEQerrno

POSIX要求設置錯誤號:

如果遇到輸出錯誤,這些函數應返回一個負值並設置errno來指示錯誤。

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

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 

看起來像在linux上使用gcc進行編譯時設置它。所以這是很好的數據,並且在man page對於errno它確實提到printf()(與sprintf()相同的家族)可能改變errno(在底部的示例中)。

+0

+1證明,但Cubbi的答案發現更具體的文件。 – cpburnz 2013-02-09 16:34:29

+0

請注意,「嘗試它」方法依賴於標準兼容的實現以及不允許空間用於不同行爲的標準。有時候這種方法會誤導你... – skyking 2017-12-20 15:38:55