Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.11Formatted I/O 159


Thefgetposfunction stores the current value of the file’s position indicator in the
object pointed to bypos.This value can be used in a later call tofsetposto reposition
the stream to that location.

5.11 For matted I/O


Formatted Output


Formatted output is handled by the fiveprintffunctions.
#include <stdio.h>
int printf(const char *restrictformat,...);
int fprintf(FILE *restrictfp,const char *restrictformat,...);
int dprintf(intfd,const char *restrictformat,...);
All three return: number of characters output if OK, negative value if output error
int sprintf(char *restrictbuf,const char *restrictformat,...);
Returns: number of characters stored in array if OK, negative value if encoding error
int snprintf(char *restrictbuf,size_tn,
const char *restrictformat,...);
Returns: number of characters that would have been stored in array
if buffer was large enough, negative value if encoding error
Theprintffunction writes to the standardoutput,fprintfwrites to the specified
stream, dprintf writes to the specified file descriptor,andsprintf places the
formatted characters in the arraybuf.Thesprintffunction automatically appends a
null byte at the end of the array,but this null byte is not included in the return value.
Note that it’s possible forsprintfto overflow the buffer pointed to bybuf.The
caller is responsible for ensuring that the buffer is large enough. Because buffer
overflows can lead to program instability and even security violations,snprintfwas
introduced. With it, the size of the buffer is an explicit parameter; any characters that
would have been written past the end of the buffer arediscarded instead. The
snprintffunction returns the number of characters that would have been written to
the buffer had it been big enough. As withsprintf,the return value doesn’t include
the terminating null byte. Ifsnprintfreturns a positive value less than the buffer size
n,then the output was not truncated. If an encoding error occurs,snprintfreturns a
negative value.
Althoughdprintfdoesn’t deal with a file pointer, we include it with the rest of the
related functions that handle formatted output. Note that usingdprintfremoves the
need to callfdopento convert a file descriptor into a file pointer for use withfprintf.
The format specification controls how the remainder of the arguments will be
encoded and ultimately displayed. Each argument is encoded according to a
conversion specification that starts with a percent sign (%). Except for the conversion
Free download pdf