snprintf和printf的区别

snprintf函数说明

int snprintf(char *restrict buf, size_t n, const char * restrict   format, ...);

函数说明:最多从源串中拷贝 n1 个字符到目标串中,然后再在后面加一个 0 。所以如果目标串的大小为 n 的话,将不会溢出。

函数返回值:若成功则返回存入数组的字符数,若编码出错则返回负值。

Result1( 推荐的用法 )

       1 #include <stdio.h>

      2 #include <stdlib.h>

       3

       4 int main()

       5 {

       6

       7      char str[10];

       8      snprintf(str,sizeof(str) ,"0123456789012345678");

       9      printf("str = %s /n",str);

      10      return 0;

      11 }

root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf     

str = 012345678

 

Result2:(不推荐使用)

       1 #include <stdio.h>

       2 #include <stdlib.h>

       3

       4 int main()

       5 {

       6

       7      char str[10];

       8      snprintf(str,18,"0123456789012345678");

       9      printf("str = %s /n",str);

      10      return 0;

      11 }

root@darkstar:/home/zhangl/unixtest/chapter9# ./testsprintf                    

str = 01234567890123456

 

snprintf函数返回值的测试:

        1 #include <stdio.h>
        2 #include <stdlib.h>
        3
        4    int main()
        5 {
        6        char str[10];
        7        int n=0;
        8
        9        n=snprintf(str,sizeof(str),"%s","abc");
       10        printf("str = %s /n",str);
       11        printf("n=%d/n",n);
       12
       13        return 0;
       14 }

Result:

root@darkstar:/home/zhangl/test # ./testsnprintf    
str = abc
n=3

 

一、测试程序一


17 int main(int argc,char **argv)
18 {
19 char buff1[256]={0};
20 char buff2[256]={0};
21 strncpy(buff1, "Hello, buffer 1!", 256);
22 strncpy(buff2, "Hello, buffer 2!", 256);
23 sprintf(buff1, "%s, does it work?", buff1);
24 snprintf(buff2, 256, "%s, does it work?", buff2);
25 printf("buffer 1: %s/n", buff1);
26 printf("buffer 2: %s/n", buff2);
27 return 0;
28 }

二、测试程序二

#include <stdio.h>
using namespace std;
int main()
{
char buf[100];
sprintf(buf, "%.*s", 4, "fluke");
printf("%s/n", buf);
memset(buf, 0, sizeof(buf));
snprintf(buf, 3, "%s", "fluke");
printf("%s/n", buf);
return 0;
}

snprintf函数并不是标准c/c++中规定的函数,但是在许多编译器中,厂商提供了其实现的版本。
在gcc中,该函数名称就snprintf,而在VC中称为_snprintf。
  由于不是标准函数,没有一个统一的标准来规定该函数的行为,所以导致了各厂商间的实现版本可
能会有差异。今天也的的确确看到了差异,因为这个小小的差异是我的程序无法正常的处理数据。
  这个小小的差异发生在count参数。在VC中,这个count就是要写入的总字符串字符数,例如:
    

// VC
int main( int argc, char * argv[])
...
{
    
char    buff[ 100
];
     printf(
" %d " ,_snprintf(buff, 10 , " 1234567890ab "
));
     printf(
" %s "
,buff);
    
return 0
;
}


// Linxu:gcc/g++
#include < stdio.h >
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。
  如果不了解这些函数在各平台间的差异,也许我们的程序在移植过程中会变得很脆弱。我们应该小心各种各样
的陷阱。

 

下面是MSDN对_snprintf函数的解释:

int _snprintf( char
 *buffer

, size_t
 count

, const char
 *format

 [, argument

] ... );
Parameters
buffer
Storage location for output
count
Maximum number of characters to store
format
Format-control string
argument
Optional arguments
Libraries

All versions of the C run-time libraries.

Return Value

_snprintf returns the number of bytes stored in buffer , not counting the terminating null character. If the number of bytes required to store the data exceeds count , then count bytes of data are stored in buffer and a negative value is returned.

Remarks

The _snprintf function formats and stores count or fewer characters and values (including a terminating null character that is always appended unless count is zero or the formatted string length is greater than or equal to count characters) in buffer. Each argument (if any) is converted and output according to the corresponding format specification in format . The format consists of ordinary characters and has the same form and function as the format argument for printf . If copying occurs between strings that overlap, the behavior is undefined.

 

 

文章来自:http://hi.baidu.com/jetqu2003/blog/item/5343b023700cf4549922ed8e.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
snprintfprintf 和 fprintf 都是 C/C++ 语言中常用的输出函数,它们的主要区别在于输出的位置和方式。 1. printf printf 是 C/C++ 标准库中的一个函数,主要用于将格式化的字符串输出到标准输出(stdout)。其格式为: ```c++ int printf(const char *format, ...); ``` 其中,format 是格式化字符串,... 是可变参数列表。printf 函数会根据 format 中的格式说明符,将可变参数列表中的值转换为字符串,并输出到标准输出。 例如: ```c++ printf("Hello, %s!\n", "world"); ``` 输出结果为: ``` Hello, world! ``` 2. fprintf fprintfprintf 类似,也是将格式化的字符串输出到指定的流中。其格式为: ```c++ int fprintf(FILE *stream, const char *format, ...); ``` 其中,stream 是输出流,可以是标准输出(stdout)、标准错误输出(stderr)或者文件流。其他参数与 printf 相同。 例如: ```c++ fprintf(stdout, "Hello, %s!\n", "world"); ``` 输出结果与 printf 相同。 3. snprintf snprintf 也是将格式化的字符串输出到指定的缓冲区中。与 fprintf 不同的是,snprintf 可以指定输出缓冲区的大小,避免缓冲区溢出的问题。其格式为: ```c++ int snprintf(char *str, size_t size, const char *format, ...); ``` 其中,str 是输出缓冲区,size 是缓冲区大小限制,format 和可变参数与其他函数相同。snprintf 函数会将格式化后的字符串输出到 str 中,最多输出 size - 1 个字符,并在末尾添加 '\0'。 例如: ```c++ char buf[10]; snprintf(buf, 10, "Hello, %s!", "world"); printf("%s\n", buf); ``` 输出结果为: ``` Hello, wo ``` 因为缓冲区大小为 10,输出字符串长度为 9,因此只输出前 9 个字符,并在末尾添加 '\0'。 总之,三个函数都是用于输出格式化字符串的,区别在于输出位置和方式,具体使用应根据实际需求选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值