在msvc2008上從失敗的vsnprintf恢復graceflly。

[英]Recovering graceflly from a failed vsnprintf on msvc2008


I'm looking for a way to use some variant of vsnprintf() with a buffer that can possibly be longer than the input buffer without triggering an error to the user.

我正在尋找一種使用vsnprintf()的變體的方法,它的緩沖區可能比輸入緩沖區長,而不會觸發用戶的錯誤。

So far I've found that vsnprintf() and its variants silently truncate the string when the buffer is too small but they don't return the actual length of the string so I can't try it again with a longer buffer. They return -1.

到目前為止,我發現vsnprintf()和它的變體在緩沖區太小時,靜默地截斷字符串,但是它們不返回字符串的實際長度,所以我不能再用一個更長的緩沖區來嘗試它。他們返回1。

On the other hand, the vsnprintf_s() variants, when faced with this error, call

另一方面,當面對這個錯誤時,vsnprintf_s()變量調用。

_VALIDATE_RETURN(("Buffer too small", 0), ERANGE, -1);

Which in turn eventually calls _CrtDbgReportW(), possibly only in debug. They do this even before calling the user supplied "invalid parameter handler"

最終調用_CrtDbgReportW(),可能只是在調試中。在調用用戶提供的“無效參數處理程序”之前,他們會這樣做

All I want is to be able to recover with no user interaction by getting the actual size I need to allocate and calling the function again. is that possible?

我想要的是能夠通過獲取實際大小來恢復沒有用戶交互,我需要重新分配和調用這個函數。這有可能嗎?

2 个解决方案

#1


2  

The function you're looking for is _vscprintf (or _vscwprintf). These return the number of characters required without actually formatting anything.

您正在尋找的函數是_vscprintf(或_vscwprintf)。這些返回了所需字符的數量,而無需實際格式化任何內容。

#2


0  

if you supply the length of the output buffer in n, you then know that no more than n characters was written.

如果您在n中提供了輸出緩沖區的長度,那么您就知道不會有超過n個字符被寫入。

vsnprintf returns the number of characters that would have been written if the buffer was long enough.

如果緩沖區足夠長,vsnprintf將返回寫入的字符數。

So, the return value is the size of the buffer you need.

因此,返回值就是所需的緩沖區的大小。

If you set n=0, nothing will be written, but vsnprintf will tell you how big the buffer needs to be.

如果您設置n=0,則不會有任何寫入,但是vsnprintf將告訴您緩沖區需要多大。

(I just re-read the vsnprintf doc, you need to add 1 byte to the return value for the NUL.)

(我只是重新讀取了vsnprintf文檔,您需要為NUL添加1字節的返回值。)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/03/24/724f2007db765d155944949934b0e986.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com