[英]variable argument function in C
I have a variable list function 我有一个变量列表功能
/* vsprintf example */
#include <stdio.h>
#include <stdarg.h>
void PrintFError (char * format, ...)
{
char buffer[50];
va_list args;
va_start (args, format);
vsprintf (buffer,format, args);
perror (buffer);
va_end (args);
}
int main ()
{
FILE * pFile;
char szFileName[]="myfile.txt";
int firstchar = (int) '#';
pFile = fopen (szFileName,"r");
if (pFile == NULL)
PrintFError ("Error opening '%s'",szFileName);
else
{
// file successfully open
fclose (pFile);
}
return 0;
}
In above example how can we check the received message in "PrintError" function that we are not crossing the buffer size in this example 50 while using "vsprintf" in above example. 在上面的示例中,我们如何在“ PrintError”函数中检查接收到的消息,即在该示例50中使用“ vsprintf”时,我们在示例50中未超过缓冲区大小。 This should be achieved in portable way. 这应该以可移植的方式实现。
您应该使用更安全的vsnprintf,并将其限制为最多50个字符。
int vsnprintf(char *str, size_t size, const char *format, va_list args);
You can use vsnprintf . 您可以使用vsnprintf 。 This is, strictly speaking, non-standard unless you have a C99 compiler, but is supported on most environments. 严格来说,这是非标准的,除非您具有C99编译器,但大多数环境都支持。 If you do not have an implementation of vsnprintf
on your platform, you can simply add a portable implementation to your program. 如果您的平台上没有vsnprintf
的实现,则只需将可移植的实现添加到程序中即可。
Use vsnprintf()
. 使用vsnprintf()
。 It allows you to specify the number of characters to output ( n
): 它允许您指定要输出的字符数( n
):
int vsnprintf(char *s, size_t n, const char *format, va_list ap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.