zoukankan      html  css  js  c++  java
  • [misc]printf/fprintf/sprintf/snprintf函数

    转自:http://blog.csdn.net/To_Be_IT_1/article/details/32179549

    需要包含的头文件

    #include <stdio.h>
    • int printf(const char *format, ...);
    • int fprintf(FILE *stream, const char *format, ...);
    • int sprintf(char *str, const char *format, ...);
    • int snprintf(char *str, size_t size, const char *format, ...);

    1. printf是标准的输出函数

    2. fprintf传送格式化输出到一个文件中

    根据指定的format(格式)发送信息(参数)到由stream(流)指定的文件,fprintf只能和printf一样工作。若成功则返回值是输出的字符数,发生错误时返回一个负值。第一个参数是文件指针stream,后面的参数就是printf中的参数,其功能就是把这些输出送到文件指针指定的文件中(使用方式一),如果想要像printf一样将输出送到标准输出,只需要将文件指针FILE指定为stdout即可(使用方式二)

    两种使用方法,一种是将字符串输入到制定文件中,一种是输出到标准输出口。

    示例程序如下:

    #include <stdio.h>  
      
    FILE *stream;  
    int  
    main(void)  
    {  
        char s[] = "this is a string.
    ";  
        char c = '
    ';  
      
        stream = fopen("fprintf.out", "w");  
        fprintf(stream, "%s", s);    //使用方式一
        fprintf(stdout, "abc
    ");    //使用方式二
        return 0;  
    }  

    该程序的运行结果是在fprintf.out文件中存入了this is a string.字符串,在标准输出输出了abc字符串。

    3. sprintf,字符串格式化命令

    主要功能是把格式化的数据写入某个字符串中。第一个参数str是char型指针,指向将要写入的字符串的缓冲区。后面第二个参数是格式化字符串。

    当src的长度大于或者等于dest的长度,则会发生内存溢出,所以是不安全的

    示例程序:

    #include <stdio.h>  
      
    int  
    main(void)  
    {  
        char s[100];   
      
        sprintf(s, "%%sfjdksfj" );  
        printf("%s
    ", s);  
        return 0;  
    }  

    执行后输出结果是

    %sfjdksfj  

    3. snprintf函数与sprintf函数类似

    snprintf较sprintf更加安全,它也是将可变个参数按照format格式化成字符串,然后将其复制到str中。

    • 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符('');
    • 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符(''),返回值为格式化后的字符串的长度。

    示例程序

    #include <stdio.h>  
      
    int  
    main(void)  
    {  
        char s[10];   
      
        snprintf(s, 4, "%%sfjdksfj" );  
        printf("%s
    ", s);  
        snprintf(s, sizeof(s), "%%sfjdksfj" );  
        printf("%s
    ", s);  
        return 0;  
    }  

    运行结果:

    %sf
    %sfjdksfj
  • 相关阅读:
    iOS resign code with App Store profile and post to AppStore
    HTTPS科普扫盲帖 对称加密 非对称加密
    appid 评价
    使用Carthage安装第三方Swift库
    AngularJS:何时应该使用Directive、Controller、Service?
    xcode7 The operation couldn't be completed.
    cocoapods pod install 安装报错 is not used in any concrete target
    xcode7 NSAppTransportSecurity
    learning uboot how to set ddr parameter in qca4531 cpu
    learning uboot enable protect console
  • 原文地址:https://www.cnblogs.com/aaronLinux/p/6686802.html
Copyright © 2011-2022 走看看