printf, fprintf, sprintf,snprintf difference

Source: Internet
Author: User
Tags sprintf
1.4 Types of formatted output differences

PRINTF,FPRINTF,SPRINTF are formatted output commands, and their usage and differences can be viewed through Linux commands "man printf".
int printf (const char *format,***) Prints the format to the STDOUT
The int fprintf (file *steam,const char *format,***) formats the output to the file stream, which is written to the file
The int sprintf (char *str,const char *format,***) formats the output into string str, noting that there is a need to allocate large enough space in advance to Str. The most common scenario for sprintf is to convert integers to strings and replace atoi functions.
The int snprintf (char *str,size_t n,const char *format,***) formats the output into string str, but writes only the output of length n. 2. Notice when formatting the output

sprintf () When converting integers, consider the format of the output number, such as

sprintf (str, "%4x",-1);

What is the value of str? The time test found that Str was ffffffff rather than a 4-bit wide FFFF. Because the function parameter is not known on the stack computer-1 is 32-bit or 16-bit, will be stored according to 32 bits, and high is the symbol bit extension, when the format of the output, 4 bit width is not enough, will automatically fill 32 bits, so the correct form should be:

sprintf (str, "%4x", (unsigned short)-1);

Similarly, if the output integer is output in floating-point format, writing:

sprintf (str, "%5.3x", 3);

The final str is 0.000 because the computer store 3 o'clock is stored as an integer, and the floating-point output must be wrong. should be

sprintf (str, "%5.3x", (float) 3);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.