Team BBL
Previous Page Next Page

5.11. Formatted I/O

Formatted Output

Formatted output is handled by the four printf functions.

#include <stdio.h>

int printf(const char *restrict format, ...);

int fprintf(FILE *restrict fp, const char
 *restrict format, ...);

Both return: number of characters output if OK, negative value if output error

int sprintf(char *restrict buf, const char
 *restrict format, ...);

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

Both return: number of characters stored in array if OK, negative value if encoding error


The printf function writes to the standard output, fprintf writes to the specified stream, and sprintf places the formatted characters in the array buf. The sprintf function 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 for sprintf to overflow the buffer pointed to by buf. It's the caller's responsibility to ensure that the buffer is large enough. Because this can lead to buffer-overflow problems, snprintf was 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 are discarded instead. The snprintf function returns the number of characters that would have been written to the buffer had it been big enough. As with sprintf, the return value doesn't include the terminating null byte. If snprintf returns a positive value less than the buffer size n, then the output was not truncated. If an encoding error occurs, snprintf returns a negative value.

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 specifications, other characters in the format are copied unmodified. A conversion specification has four optional components, shown in square brackets below:

    %[flags][fldwidth][precision][lenmodifier]convtype

The flags are summarized in Figure 5.7.

Figure 5.7. The flags component of a conversion specification

Flag

Description

-

left-justify the output in the field

+

always display sign of a signed conversion

(space)

prefix by a space if no sign is generated

#

convert using alternate form (include 0x prefix for hex format, for example)

0

prefix with leading zeros instead of padding with spaces


The fldwidth component specifies a minimum field width for the conversion. If the conversion results in fewer characters, it is padded with spaces. The field width is a non-negative decimal integer or an asterisk.

The precision component specifies the minimum number of digits to appear for integer conversions, the minimum number of digits to appear to the right of the decimal point for floating-point conversions, or the maximum number of bytes for string conversions. The precision is a period (.) followed by a optional non-negative decimal integer or an asterisk.

Both the field width and precision can be an asterisk. In this case, an integer argument specifies the value to be used. The argument appears directly before the argument to converted.

The lenmodifier component specifies the size of the argument. Possible values are summarized in Figure 5.8.

Figure 5.8. The length modifier component of a conversion specification

Length modifier

Description

hh

signed or unsigned char

h

signed or unsigned short

l

signed or unsigned long or wide character

ll

signed or unsigned long long

j

intmax_t or uintmax_t

z

size_t

t

ptrdiff_t

L

long double


The convtype component is not optional. It controls how the argument is interpreted. The various conversion types are summarized in Figure 5.9.

Figure 5.9. The conversion type component of a conversion specification

Conversion type

Description

d,i

signed decimal

o

unsigned octal

u

unsigned decimal

x,X

unsigned hexadecimal

f,F

double floating-point number

e,E

double floating-point number in exponential format

g,G

interpreted as f, F, e, or E, depending on value converted

a,A

double floating-point number in hexadecimal exponential format

c

character (with l length modifier, wide character)

s

string (with l length modifier, wide character string)

p

pointer to a void

n

pointer to a signed integer into which is written the number of characters written so far

%

a % character

C

wide character (an XSI extension, equivalent to lc)

S

wide character string (an XSI extension, equivalent to ls)


The following four variants of the printf family are similar to the previous four, but the variable argument list (...) is replaced with arg.

#include <stdarg.h>
#include <stdio.h>

int vprintf(const char *restrict format, va_list arg);

int vfprintf(FILE *restrict fp, const char
 *restrict format,
             va_list arg);

Both return: number of characters output if OK, negative value if output error

int vsprintf(char *restrict buf, const char
 *restrict format,
             va_list arg);

int vsnprintf(char *restrict buf, size_t n,
              const char *restrict format, va_list
 arg);

Both return: number of characters stored in array if OK, negative value if encoding error


We use the vsnprintf function in the error routines in Appendix B.

Refer to Section 7.3 of Kernighan and Ritchie [1988] for additional details on handling variable-length argument lists with ISO Standard C. Be aware that the variable-length argument list routines provided with ISO Cthe <stdarg.h> header and its associated routinesdiffer from the <varargs.h> routines that were provided with older UNIX systems.

Formatted Input

Formatted input is handled by the three scanf functions.

#include <stdio.h>

int scanf(const char *restrict format, ...);

int fscanf(FILE *restrict fp, const char *restrict
 format, ...);

int sscanf(const char *restrict buf, const char
 *restrict format,
           ...);

All three return: number of input items assigned,
EOF if input error or end of file before any conversion


The scanf family is used to parse an input string and convert character sequences into variables of specified types. The arguments following the format contain the addresses of the variables to initialize with the results of the conversions.

The format specification controls how the arguments are converted for assignment. The percent sign (%) indicates the start of a conversion specification. Except for the conversion specifications and white space, other characters in the format have to match the input. If a character doesn't match, processing stops, leaving the remainder of the input unread.

There are three optional components to a conversion specification, shown in square brackets below:

    %[*][fldwidth][lenmodifier]convtype

The optional leading asterisk is used to suppress conversion. Input is converted as specified by the rest of the conversion specification, but the result is not stored in an argument.

The fldwidth component specifies the maximum field width in characters. The lenmodifier component specifies the size of the argument to be initialized with the result of the conversion. The same length modifiers supported by the printf family of functions are supported by the scanf family of functions (see Figure 5.8 for a list of the length modifiers).

The convtype field is similar to the conversion type field used by the printf family, but there are some differences. One difference is that results that are stored in unsigned types can optionally be signed on input. For example, 1 will scan as 4294967295 into an unsigned integer. Figure 5.10 summarizes the conversion types supported by the scanf family of functions.

Figure 5.10. The conversion type component of a conversion specification

Conversion
type

Description

d

signed decimal, base 10

i

signed decimal, base determined by format of input

o

unsigned octal (input optionally signed)

u

unsigned decimal, base 10 (input optionally signed)

x

unsigned hexadecimal (input optionally signed)

a,A,e,E,f,F,g,G

floating-point number

c

character (with l length modifier, wide character)

s

string (with l length modifier, wide character string)

[

matches a sequence of listed characters, ending with ]

[^

matches all characters except the ones listed, ending with ]

p

pointer to a void

n

pointer to a signed integer into which is written the number of characters read so far

%

a % character

C

wide character (an XSI extension, equivalent to lc)

S

wide character string (an XSI extension, equivalent to ls)


As with the printf family, the scanf family also supports functions that use variable argument lists as specified by <stdarg.h>.

#include <stdarg.h>
#include <stdio.h>

int vscanf(const char *restrict format, va_list arg);

int vfscanf(FILE *restrict fp, const char
 *restrict format,
            va_list arg);

int vsscanf(const char *restrict buf, const char
 *restrict format,
            va_list arg);

All three return: number of input items assigned,
EOF if input error or end of file before any conversion


Refer to your UNIX system manual for additional details on the scanf family of functions.

    Team BBL
    Previous Page Next Page