gpt4 book ai didi

c++ - snprintf() 返回不适当的值

转载 作者:行者123 更新时间:2023-11-28 00:16:33 24 4
gpt4 key购买 nike

我已经查看这段代码一段时间了,但似乎找不到我的错误。我想我知道 snprintf(dest, n, fmt, src) 应该如何工作(它在填充 后返回 src 缓冲区中剩余的字符数>dest 缓冲区与 fmt 字符串和 src 缓冲区中的 n 个字符),但它没有按照我的预期进行。它不返回要复制的剩余字符数,而是返回复制的总数 个字符。

下面的代码:

 40   char header_file_name[200];
....
87 int n_overflow = 0;
88 n_overflow = snprintf( header_file_name, 200, "%s.h", template_name );
89 if ( n_overflow > 0 )
90 {
91 printf( "That template name is too large; try a smaller template name\n");
92 printf("n_overflow = %d\n", n_overflow);
93 printf("header_file_name = %s\n", header_file_name );
94 printf("length of header_file_name = %d\n", strlen(header_file_name));
95 printf( "template_name = %s\n", template_name );
96 printf("length of template_name = %d\n", strlen(template_name));
97 exit(4);
98 }
99 if ( n_overflow < 0 )
100 {
101 printf( "An error occurred while handling your input; file: %s, line:%d\n", __FILE__, __LINE__);
102 exit(1);
103 }

输出如下:

Compiling template file ABAQUS_Version_5.template
That template name is too large; try a smaller template name
n_overflow = 18
header_file_name = ABAQUS_Version_5.h
length of header_file_name = 18
template_name = ABAQUS_Version_5
length of template_name = 16
*** Error code 4
clearmake: Error: Build script failed for "ABAQUS_Version_5.o"

令人困惑的是我的 dest (header_file_name) 有一个长度,甚至在 snprintf() 之后还有数据> 调用,我的 src (template_name) 也有一个长度并且不是 NULL。我可能只是在我的代码中犯了一些错误,或者我不太了解 snprintf(),并且已经主演它太久了。任何帮助将不胜感激!

最佳答案

这就是 snprintf 应该做的。

来自 Ubuntu 系统上的 man snprintf:(强调)

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated.

或者,来自 Posix 的更简单的措辞:

Upon successful completion, the snprintf() function shall return the number of bytes that would be written to s had n been sufficiently large excluding the terminating null byte.

关于c++ - snprintf() 返回不适当的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com