首页 > 编程知识 正文

snprintf sprintf,c语言中snprintf

时间:2023-05-06 10:51:15 阅读:259312 作者:1101

一、snprintf与snprintf_s的区别

众所周知,sprintf不能检查目标字符串的长度,可能造成众多安全问题,所以都会推荐使用snprintf.

snprintf函数在C++11之前 并不是标准c/c++中规定的函数,但是在许多编译器中,厂商提供了其实现的版本。

在gcc中,该函数名称就snprintf,而在VC中称为_snprintf,后面提供了更安全的s_nprintf_s。

由于不是标准函数,没有一个统一的标准来规定该函数的行为,所以导致了各厂商间的实现版本可

能会有差异。今天也的的确确看到了差异,因为这个小小的差异是我的程序无法正常的处理数据。

这个小小的差异发生在count参数。在VC中,这个count就是要写入的总字符串字符数,例如:

//VC

int main(int argc, char * argv[])

{

char buff[100];

printf("%d ",_snprintf_s(buff,10,"1234567890ab"));

printf("%s",buff);

return 0;

}

//Linxu:gcc/g++

#include

int main(int argc, char * argv[])

{

char buff[100];

printf("%d ",snprintf(buff,10,"1234567890ab"));

printf("%s",buff);

return 0;

}

vc程序的输出是:

-1

1234567890@

gcc程序的输出是:

12

123456789

从输出结果可以知道:

VC中的_snprintf的count参数表示,会向buff中写入count个字符,不包括'/0'字符,并且不会在字符串末尾添加'/0'符,并且,如果字符串超过count,函数返回-1以标志可能导致的错误;

gcc中的snprintf函数的count参数表示,向buff中写入10个字符,包括'/0'字符,并且,返回实际的字符串长度,例子中为12。

如果不了解这些函数在各平台间的差异,也许我们的程序在移植过程中会变得很脆弱。我们应该小心各种各样

的陷阱。

C++11里面的snprintf与GCC中是一样的概念:

s

Pointer to a buffer where the resulting C-string is stored.

The buffer should have a size of at least n characters.

n

Maximum number of bytes to be used in the buffer.

The generated string has a length of at most n-1,leaving space for the additional terminating null character.

size_t is an unsigned integral type.

return

The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character.

If an encoding error occurs, a negative number is returned.

Notice that only when this returned value is non-negative and less than n, the string has been completely written.

二、C++里面对64位整数不同平台的表示方法

linux下是

printf("%lld/n",a);

printf("%llu/n",a);

windows下是

printf("%I64d/n",a);

printf("%I64u/n",a);

三、64位在不同平台下的定义

long long定义方式可以用于gcc/g++,不受平台限制,但不能用于VC6.0。

__int64是Win32平台编译器64位长整型的定义方式,不能用于Linux。

"%lld"用于Linux i386平台编译器,"%I64d"用于Win32平台编译器。

cout只能用于C++编译,在VC6.0中,cout不支持64位长整型。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。