13.16 <cstdio>

The <cstdio> header is a wrapper for the C standard <stdio.h> header, which declares input and output types, macros, and functions. See also <cwchar> for wide character I/O functions.

C++ I/O streams offer more flexibility, type-safety, and clarity. On the other hand, C I/O offers simplicity and compatibility with C libraries. See Chapter 9 for an overview of the C++ I/O stream classes.

_IOFBF macro Full buffering

int _IOFBF

When passed as the mode parameter to setvbuf, the _IOFBF macro sets an open file to full buffering. A buffer is flushed when it is full. The _IOFBF macro expands to a constant integer.

figs/acorn.gif

Support for fully-buffered streams is implementation-dependent.

See Also

setvbuf function

_IOLBF macro Line buffering

int _IOLBF

When passed as the mode parameter to setvbuf, the _IOLBF macro sets an open file to line buffering. A buffer is flushed when it is full or when a newline character is read or written. The _IOLBF macro expands to a constant integer.

figs/acorn.gif

Support for line-buffered streams is implementation-dependent.

See Also

setvbuf function

_IONBF macro No buffering

const int _IONBF

When passed as the mode parameter to setvbuf, the _IONBF macro disables the buffering of an open file. Characters are read or written as soon as possible, without buffering. The _IONBF macro expands to a constant integer.

figs/acorn.gif

Support for unbuffered streams is implementation-dependent. For example, a host operating system might line buffer input from a terminal, even if a program requests unbuffered input.

See Also

setvbuf function

BUFSIZ macro Buffer size

int BUFSIZ

The BUFSIZ macro specifies the minimum buffer size for the setbuf function. The BUFSIZ macro expands to a constant integer.

See Also

setbuf function, setvbuf function

clearerr function Clears error status

void clearerr(FILE* stream)

The clearerr function clears the error and end-of-file indicators for stream.

See Also

feof function, ferror function

EOF macro End-of-file or error

int EOF

The EOF macro represents end-of-file when returned from getchar and other functions. Some functions return EOF to indicate an error.

figs/acorn.gif

The value of EOF is a negative integer constant. The precise value is implementation-defined.

fclose function Closes a file

int fclose(FILE* stream)

The fclose function flushes and closes an open file. It returns 0 upon success or EOF when there is an error.

See Also

fopen function

feof function Tests for end-of-file

int feof(FILE* stream)

The feof function returns true (nonzero) if stream is positioned at the end-of-file, or false (0) otherwise.

See Also

clearerr function, ferror function

ferror function Tests for error

int ferror(FILE* stream)

The ferror function returns true (nonzero) if stream has an error condition set, or false (0) otherwise.

See Also

clearerr function, feof function

fgetc function Reads a character

int fgetc(FILE* stream)

The fgetc function reads a single character from stream. It returns the character as an unsigned char converted to int or EOF for an error or end-of-file.

See Also

feof function, ferror function, getc macro, fputc function, fwgetc in <cwchar>

fgetpos function Returns file position

int fgetpos(FILE* stream, fpos_t* pos)

The fgetpos function stores stream's current position in the object that pos points to. The only use for the position is to save it and pass it to fsetpos to set the file's position. You cannot use the position arithmetically, e.g., to advance the position by one character.

The return value is 0 for success or nonzero for failure. If fgetpos fails, it sets errno.

See Also

fpos_t type, fsetpos function, ftell function

fgets function Reads a string

char* fgets(char* s, int n, FILE* stream)

The fgets function reads a line of text from stream into the character array that s points to. It stops reading after a newline character or after n - 1 characters have been read. The newline character, if one is encountered, is copied into s.

The return value is s for success or a null pointer for an error or end-of-file. If fgets fails, the contents of the string s are undefined.

See Also

fgetc function, getc macro, fputs function, fwgets in <cwchar>

FILE type File type

typedef  . . .  FILE

The FILE type represents the contents of an external file. A C++ program works with FILE pointers, in which the actual FILE objects are managed by functions in the standard library. Thus, you never need to allocate or free FILE objects.

See Also

fclose function, fopen function, freopen function, <fstream>

FILENAME_MAX macro Maximum length of a filename

int FILENAME_MAX

FILENAME_MAX is the size you should use when declaring a character array that will store a filename. Some systems do not have a fixed maximum size for a filename, in which case FILENAME_MAX is a recommended size, and the resulting character array might not be large enough to hold all valid filenames. The FILENAME_MAX macro expands to a constant integer.

Use std::string instead of a character array to avoid any problems with character arrays that are too small.

fopen function Opens a file

FILE* fopen(const char* filename, const char* mode)

The fopen function opens a file.

figs/acorn.gif

The filename parameter specifies the filename in an implementation-defined manner. The mode parameter specifies how to open the file. The mode must begin with one of the strings listed in Table 13-4. Additional characters can follow, and the interpretation of the extra characters is implementation-defined. Mode strings are case-sensitive.

Table 13-4. File open modes

Mode string

Description

a

Append: opens an existing file for appending, that is, every write is forced to the end of the file. If the file to be opened does not exist, a creates it.

r

Read: opens an existing file for reading.

w

Write: creates a new file for writing. If the file already exists, w truncates it to zero length.

ab

Append in binary mode.

rb

Read in binary mode.

wb

Write in binary mode.

a+

Append update: opens a file in append mode and allows it to be read.

r+

Read update: opens an existing file for reading, and also allows writing.

w+

Write update: creates a new file for writing, and also allows reading. If the file already exists, w+ truncates it to zero length.

ab+ or a+b

Append update in binary mode.

rb+ or r+b

Read update in binary mode.

wb+ or w+b

Write update in binary mode.

See Also

fclose function, freopen function

FOPEN_MAX macro Minimum limit on the number of open files

int FOPEN_MAX

A typical operating system has a maximum number of files that can be open at one time. This number might be variable or fixed; FOPEN_MAX is the guaranteed minimum value of the limit. The FOPEN_MAX macro expands to a constant integer.

See Also

fopen function

fpos_t type File position

typedef  . . .  fpos_t

The fpos_t type is an opaque type that represents a position in a file. The only way to set the value of an fpos_t object is to call fgetpos, and the only things you can do with the value are assign an fpos_t value to it and pass it as a function argument, especially to fsetpos.

See Also

fgetpos function, fsetpos function, fpos in <ios>

fprintf function Writes formatted data

int fprintf(FILE* stream, const char* format,  . . . )

The fprintf function writes formatted output to stream. The format parameter contains the formatting information, and the remaining arguments are printed according to the format. The return value is the number of characters printed, or a negative value for an error.

Characters in format are printed verbatim except for conversion specifications, which begin with a percent sign (%). Each conversion specification is made up of the following parts (in order): flags, field width, precision, size, and conversion specifier.

The following are detailed descriptions of the parts of a conversion specification:

Flags

The flag characters are optional and can appear in any order. Table 13-5 lists the flag characters and their meanings.

Table 13-5. Formatting flag characters

Flag

Description

-

Left-justified (default is right-justified).

+

Signed conversions always begin with a sign (default is to use a sign only if the value is negative).

Space

The output is an initial space character if a signed conversion results in an empty string or a string that does not start with a sign character (+ takes precedence over space).

#

Use an alternate form: insert a 0 for %o; insert 0x for %x or 0X for %X; always output a decimal point for floating-point conversions; do not remove trailing zeros for %g or %G; behavior is undefined for other conversions.

0

Fields are padded with leading zeros (after the sign or base indication). The - flag takes precedence over 0. For integer conversions, a precision takes precedence over the 0 flag.

Field width

An optional number that specifies the minimum number of characters that the field will occupy. If the field is an asterisk (*), the field width is obtained from the next argument to be processed.

Precision

An optional number of digits for an integer, number of decimal digits for a floating-point number, or maximum size for a string. The precision is specified as a dot (.) followed by a number or an asterisk.

Size

The character h, l, or L. h means an integer is short or unsigned short. l means an integer is long or unsigned long, a character is wint_t, or a string is a pointer to wchar_t. L means a floating-point number is long double.

Conversion character

Specifies the type of the argument containing the data to be printed using a conversion specification. It must be one of the following:

d, i

Signed decimal integer.

o

Unsigned octal integer.

u

Unsigned decimal integer.

x, X

Unsigned hexadecimal integer. x writes the digits a-f in lowercase, and X writes the digits A-F in uppercase.

f

Fixed-precision floating point.

e, E

Exponential floating point. The exponent is introduced with e or E, matching the conversion character.

g, G

General floating point. Use style f or e. Use style e if the exponent is less than -4 or greater than the precision; otherwise, use style f. Trailing zeros are dropped, and a trailing decimal point is dropped if it would be the last character.

c

Character. The argument must be an unsigned char promoted to int, or, if the l size modifier is used, the argument must be wchar_t promoted to wint_t, which is then printed as a multibyte character.

s

String. The argument is a pointer to a null-terminated array of characters, or, if the l size modifier is used, the argument must be a pointer to a wchar_t array, which is converted to a series of multibyte characters.

figs/acorn.gifp

Pointer. The argument must be a pointer to void. The output format is implementation-defined.

n

The argument must be a pointer to an integer; fprintf stores in the integer the number of characters written so far. Use the h or l size modifiers if the argument is a pointer to short int or long int.

%

Prints a literal %.

It is your responsibility to ensure that the argument types match the format. Any errors result in undefined behavior. Mismatches between format and the argument is a common and sometimes subtle source of error. You can avoid these problems entirely by using C++ I/O streams instead of fprintf and related functions.

All the printf-related functions interpret the format string identically.

Example

The following are examples of calling printf:

long double pi = 3.141592653589792L;

int i = 42;

const char greeting[] = "Hello, how are you?";

   

printf(">%d %% %Lg<\n", i, pi); // Prints >42 % 3.14159<

printf(">%4d<\n", i);           // Prints >  42<

printf(">%-16.8Le<\n", pi);     // Prints >3.14159265e+00  <

printf(">%#*.*x<\n", 8, 4, i);  // Prints >  0x002a<

printf(">%.5s<\n", greeting);   // Prints >Hello<

See Also

fscanf function, printf function, sprintf function, vfprintf function, wcrtomb in <cwchar>, fwprintf in <cwchar>

fputc function Writes a character

int fputc(int c, FILE* stream)

The fputc function writes a single character to stream. The character must be an unsigned char, which is automatically promoted to int, so the proper way to print a variable of type char is as follows:

char ch;

fputc(static_cast<unsigned char>(ch), stream);

The return value is EOF for an error or c for success.

See Also

putc macro, fwputc in <cwchar>

fputs function Writes a string

int fputs(const char* s, FILE* stream)

The fputs function writes the string s to stream. It returns EOF for an error or a nonnegative value for success.

See Also

fputc function, puts function, fwputs in <cwchar>

fread function Reads binary data

size_t fread(void* ptr, size_t size, size_t count, FILE* stream)

The fread function reads up to count elements from stream into the memory that ptr points to. The memory must have POD type (see Chapter 6). Each element is size bytes long. It returns the number of elements that were read successfully.

See Also

fwrite function

freopen function Opens a file with an existing stream

FILE* freopen(const char* filename, const char* mode, FILE* stream)

The freopen function opens a file using an existing stream. The file previously associated with the stream is closed first, and the named file is opened in the same manner as if fopen were called. See fopen for a description of the mode parameter.

The main purpose of using freopen is to reopen one of the standard files: stdin, stdout, and stderr.

See Also

fclose function, fopen function

fscanf function Reads formatted data

int fscanf(FILE* stream, const char* format,  . . . )

The fscanf function performs a formatted read from stream. The format parameter contains formatting information, and the remaining arguments are pointers. When fscanf reads items, it stores their values in the objects that successive arguments point to. The return value is the number of items read or a negative value for an error.

Items are read from stream and interpreted according to format, which contains whitespace characters, non-whitespace characters, and conversion specifications, which begin with a percent sign (%). A whitespace character directs fscanf to skip over whitespace in the input stream. Non-whitespace characters must match the input text. Each conversion specification is made up of the following parts (in order): assignment suppression, field width, size, and conversion specifier.

The following are descriptions of the conversion specification elements:

Assignment suppression

An optional asterisk (*) directs fscanf to read and parse the input according to the conversion specification, but not to assign the value to an argument.

Field width

An optional number (positive decimal integer) that specifies the maximum number of characters to read.

Size

The character h, l, or L. h means an integer is short or unsigned short. l means an integer is long or unsigned long; a floating-point number is double, or a string argument is a pointer to wchar_t for the c, s, and [ conversion specifiers. L means a floating-point number is long double. The default size for an integer is int or unsigned int, float for a floating-point number, and char for any of the character conversion specifiers.

Conversion character

Specifies the type of the argument containing the data to be printed using a conversion specification. It must be one of the following:

d

Signed decimal integer.

i

Signed integer. Reads and interprets a prefix of 0x or 0X for hexadecimal, 0 for octal, or anything else for decimal.

o

Unsigned octal integer.

u

Unsigned decimal integer.

x, X

Unsigned hexadecimal integer.

e, E, f, g, G

Floating point in fixed or exponential format.

c

Characters. The field width (default 1) specifies the exact number of characters to read. The corresponding argument must be a pointer to a character array large enough to hold the characters. If the l modifier is used, the input is read as multibyte characters, which are converted to wide characters and stored in a wchar_t array. In either case, no null character is appended.

s

String. Reads a sequence of non-whitespace characters. The corresponding argument must be a pointer to a character array that is large enough to hold the sequence plus a terminating null character. If the l modifier is used, the input is read as multibyte characters, which are converted to wide characters and stored in a wchar_t array, followed by a terminating null wide character.

figs/acorn.gifp

Pointer. The argument must be a pointer to void. The input format is implementation-defined and matches the format that fprintf uses.

n

The argument must be a pointer to an integer; fscanf stores in the integer the number of characters read so far. The h or l size modifiers can be used if the argument is a pointer to short int or long int. Nothing is read from the input, and %n does not affect the count returned by fscanf.

[

Matches a sequence of characters. The conversion specification lists a set of characters (called the scanset) in square brackets. The input string is a sequence of characters that matches any of the characters in the scanset or, if the scanset begins with a circumflex (^), any character not in the scanset. If the l modifier is used, the input is read as multibyte characters, which are converted to wide characters and stored in a wchar_t array, followed by a terminating null wide character.

%

Matches a literal % in the input stream.

It is your responsibility to ensure that the argument types match the format. Any errors result in undefined behavior. Mismatches between format and the argument are a common and sometimes subtle source of error. You can avoid these problems entirely by using C++ I/O streams instead of fscanf and related functions.

All the scanf-related functions interpret the format string identically.

Example

The following is an example of calling scanf. The input stream is:

start 3.14 BeefFeed cab42.0e-01, 1234

and the scanf call is:

char c[10];

double d;

float f;

long int l;

unsigned short us;

scanf("start %4lf %4lx%*x %9[abcdefg]%f,%hu", &d, &l, c, &f, &us);

which has the following result:

c = "cab"

d = 3.14

f = 4.2

l = 48879 (0xbeef)

us = 1234

See Also

fprintf function, scanf function, sscanf function, vfscanf function, mbrtowc in <cwchar>, fwscanf in <cwchar>

fseek function Changes file position

int fseek(FILE* stream, long int offset, int origin)

The fseek function seeks to a different position in stream. The origin must be one of SEEK_CUR, SEEK_END, or SEEK_SET. The offset is relative to the current position, end-of-file, or start-of-file, respectively. The end-of-file flag is cleared, and any ungetc character is also cleared.

Use fsetpos instead of fseek when using large filesthat is, for which a position does not necessarily fit into a long int.

The return value is 0 for success or nonzero for an error.

See Also

fsetpos function, ftell function, SEEK_CUR macro, SEEK_END macro, SEEK_SET macro

fsetpos function Changes file position

int fsetpos(FILE* stream, const fpos_t* pos)

The fsetpos function seeks to a different position in stream. The position must have been returned from an earlier successful call to fgetpos.

See Also

fpos_t type, fseek function, fgetpos function

ftell function Returns current file position

long int ftell(FILE* stream)

The ftell function returns the current file position in stream. This position can be used (with an origin of SEEK_SET) in a subsequent call to fseek. If ftell fails, it returns -1L (which may be, but is not necessarily, the same value as EOF).

See Also

fgetpos function, fseek function

fwrite function Writes binary data

size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream)

The fwrite function writes up to count elements to stream. Each element is size bytes long, and ptr points to the first such element. The memory must have POD type (see Chapter 6).

The return value is the number of complete elements successfully written to stream.

See Also

fread function

getc macro Reads a character

int getc(FILE* stream)

The getc macro reads a character from stream and returns that character as an unsigned char. The return value is EOF for end-of-file or a read error.

See Also

fgetc function, getchar macro, putc macro

getchar macro Reads a character from stdin

int getchar(  )

The getchar macro is equivalent to getc(stdin).

See Also

fgetc function, getc macro, putchar macro

gets function Reads a string unsafely

char* gets(char* s)

The gets function reads a line of text (up to and including a newline) into the string s.

There is no way to limit the input to the size of s, so you should never call gets. Use fgets instead.

See Also

fgets function, getchar macro

L_tmpnam macro Length of temporary filename

int L_tmpnam

L_tmpnam is the length of a temporary filename for tmpnam. The L_tmpnam macro expands to a constant integer.

See Also

tmpnam function

NULL macro Null pointer constant

#define NULL  . . .

The NULL macro expands to a null pointer constant. See <cstddef> for more information.

See Also

NULL in <cstddef>

perror function Writes an error message

void perror(const char* s)

The perror function writes an error message to stderr. If s is not null and is not an empty string, it is printed first, followed by a colon and a space. The error message is printed next and is the same text as that returned by strerror, passing errno as its argument.

See Also

errno in <cerrno>, strerror in <cstring>

printf function Writes formatted data

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

The printf function is equivalent to calling fprintf to stdout. See fprintf for information about the format string.

See Also

fprintf function, vprintf function, wprintf in <cwchar>

putc macro Writes a character

int putc(int c, FILE* stream)

The putc macro writes the character c, which must be cast to unsigned char, to stream.

See Also

fputc function, putchar macro, wputc in <cwchar>

putchar macro Writes a character to stdout

int putchar(int c)

The putchar macro is equivalent to putc(c, stdout).

See Also

fputc function, putc macro, wputchar in <cwchar>

puts function Writes a string

int puts(const char* s)

The puts function writes a string to stdout.

See Also

fputs function, putc function, wputs in <cwchar>

remove function Deletes a file

int remove(const char* filename)

The remove function deletes the file named by filename. It returns 0 for success or nonzero for an error.

See Also

rename function

rename function Renames a file

int rename(const char* oldname, const char* newname)

The rename function renames the file specified by oldname to newname. The return value is 0 for success or nonzero for failure.

See Also

remove function

rewind function Resets file position

void rewind(FILE* stream)

The rewind function moves a file position to the beginning of a file and is equivalent to fseek(stream, 0, SEEK_SET).

See Also

fseek function, fsetpos function

SEEK_CUR macro Seek from current file position

int SEEK_CUR

Pass SEEK_CUR as the last parameter to fseek to seek from the current file position. Positive offset values seek toward the end of the file, and negative values seek toward the beginning of the file. The SEEK_CUR macro expands to a constant integer.

See Also

fseek function

SEEK_END macro Seek from end-of-file

int SEEK_END

Pass SEEK_END as the last parameter to fseek to seek relative to the end of the file. Positive offset values seek past the end of the file, and negative values seek toward the beginning of the file. The SEEK_END macro expands to a constant integer.

See Also

fseek function

SEEK_SET macro Seek from beginning of file

int SEEK_SET

Pass SEEK_SET as the last parameter to fseek to seek from the start of the file. Positive offset values seek toward the end of the file. The SEEK_SET macro expands to a constant integer.

See Also

fseek function

setbuf function Sets file buffer

void setbuf(FILE* stream, char* buf)

The setbuf function sets the buffer to use when reading from or writing to stream. The size of buf must be at least BUFSIZ characters.

See Also

BUFSIZ macro, setvbuf function

setvbuf function Sets file buffer

int setvbuf(FILE* stream, char* buf, int mode, size_t size)

The setvbuf function sets the buffering for stream. The mode determines the buffering mode: no buffering (_IONBF), line buffering (_IOLBF), or full buffering (_IOFBF). You can supply a buffer in the buf argument, with size as the buffer size, or use a null pointer for the buf argument to let setvbuf allocate the buffer. (The buffer will be freed when the file is closed or setvbuf is called to change the buffering.)

Call setvbuf before performing any I/O on stream.

See Also

IOFBF macro, _IOLBF macro, _IONBF macro, setbuf function

size_t type Size type

typedef  . . .  size_t;

figs/acorn.gif

The size_t type is the type of the result of the sizeof operator. It is an unsigned integral type. The exact type is implementation-defined.

See Also

size_t in <cstddef>

sprintf function Writes formatted data to a string

int sprintf(char* s, const char* format, ...)

The sprintf function is like fprintf, but instead of writing to an open file, it "writes" by copying characters to the string s. See fprintf for a description of the format parameter.

You must ensure that s is large enough for the formatted string. or some formats, this is impossible, which makes sprintf unsafe to use.

See Also

fprintf function, sscanf function, vsprintf function, wsprintf in <cwchar>, <sstream>

sscanf function Reads formatted data from a string

int sscanf