警告 1 warning C4013: “snprintf”未定义;
这种情况需要加入宏定义:
#if _MSC_VER
#define snprintf _snprintf
#endif
1、snprintf和strncpy的区别:snprintf会在字符串末尾添加字符串结束符 ‘\0’ ,strncpy不会。
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if _MSC_VER
#define snprintf _snprintf
#endif
int main()
{
char strSrc[128] = "abcdef";
char str[128] = { '\0' };
strncpy(str, strSrc, strlen(strSrc));
printf("src = %s, str = %s\n", strSrc, str);
snprintf(str, sizeof("NULL"), "%s", "NULL");
printf("src = %s, str = %s\n", strSrc, str);
system("pause");
return 0;
}
结果:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if _MSC_VER
#define snprintf _snprintf
#endif
int main()
{
char strSrc[128] = "abcdef";
char str[128] = { '\0' };
snprintf(str, sizeof(strSrc), "%s", strSrc);
printf("src = %s, str = %s\n", strSrc, str);
strncpy(str, "NULL", strlen("NULL"));
printf("src = %s, str = %s\n", strSrc, str);
system("pause");
return 0;
}
结果:
可见:strncpy不会在字符串末尾添加字符串结束符。
注意,一般在使用的时候不适用strlen求长度,一般采用sizeof。
2、strcpy() sprintf() strcat() 存在安全隐患, 其对应的安全版为:strncpy() snprintf() strncat()。
综上,使用snprintf最为妥当。