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.
You should use iostreams instead of the C I/O library. C++ iostreams offer more flexibility, type-safety, and clarity. See Chapter 10 for an overview of the iostream classes.
Full buffering
const int _IOFBF
The _IOFBF
macro sets an open file to full buffering, when passed as the mode parameter to setvbuf
. A buffer is flushed when it is full.
Support for unbuffered streams is implementation-dependent.
setvbuf function
Line buffering
const int _IOLBF
The _IOLBF
macro sets an open file to line buffering when passed as the mode parameter to setvbuf
. A buffer is flushed when it is full or when a newline character is read or written.
Support for unbuffered streams is implementation-dependent.
setvbuf function
No buffering
const int _IONBF
The _IONBF
macro disables buffering of an open file when passed as the mode parameter to setvbuf
. Characters are read or written as soon as possible, without buffering.
Support for unbuffered streams is implementation-dependent. For example, a host operating system might line buffer input from a terminal, even if the program request unbuffered input.
setvbuf function
Buffer size
const int BUFSIZ
The BUFSIZ
macro specifies the buffer size for the setbuf
function.
setbuf function, setvbuf function
Clear error status
void clearerr(FILE* stream)
The clearerr
function clears the error and end-of-file indicators for stream
.
feof function, ferror function
End of file or error
const int EOF
The EOF
macro represents end-of-file when returned from getchar
and other functions. Some functions return EOF
to indicate any error.
The value of EOF
is a negative integer. The precise value is implementation defined.
Closes a file
int fclose(FILE* stream)
The fclose
function flushes and closes an open file. It returns 0 for success or EOF
for an error.
fopen function
Tests for end of file
int feof(FILE* stream)
The feof
function returns true (non-zero) if stream
is positioned at the end of file, or false (zero) otherwise.
clearerr function, ferror function
Tests for error
int ferror(FILE* stream)
The ferror
function returns true (non-zero) if stream
has an error condition set, or false (zero) otherwise.
clearerr function, feof 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 it returns EOF
for an error or end of file.
feof function, ferror function, getc macro, fputc function, fwgetc in <cwchar>
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 zero for success or non-zero for failure. If fgetpos
fails, it sets errno
.
fsetpos function, ftell 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 is copied into s
.
The return value is s
for success or NULL
for an error or end-of-file. If fgets
fails, the contents of the string s
are undefined.
fgetc function, getc macro, fputs function, fwgets in <cwchar>
File type
typedef ... FILE
The FILE
type represents the contents of an external file. A C++ program works with FILE
pointers, where the actual FILE
objects are managed by functions in the standard library. Thus, you never need to allocate or free FILE
objects.
fclose function, fopen function, freopen function
Maximum length of a file name
const int FILENAME_MAX
FILENAME_MAX
is the size you should use when declaring a character array that is to store a file name. Some systems do not have a fixed maximum size of a file name, in which case, FILENAME_MAX
is a recommended size, so the character array might not be large enough to hold all valid file names.
Use std::string
instead of a character array to avoid any problems with too-small character arrays.
Opens a file
FILE* fopen(const char* filename, const char* mode)
The fopen
function opens a file.
The filename
parameter specifies the file name 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 character can follow, and the interpretation of the extra characters is implementation-defined.
Mode string | Description |
---|---|
a |
append: open an existing file or create a new file for appending |
r |
Read: open an existing file for reading |
w |
Write: truncate an existing file to zero length or create a new file for writing |
ab |
Append in binary mode |
rb |
Read in binary mode |
wb |
Write in binary mode |
a+ |
Append for reading and writing (updating) at end of file |
r+ |
Read an existing file for reading and writing |
w+ |
Truncate or create a new file reading and writing |
ab+ or a+b |
Append for updating in binary mode |
rb+ or r+b |
Update in binary mode |
wb+ or w+b |
Truncate or create for updating in binary mode |
fclose function, freopen function
Minimum number of open files
const int FOPEN_MAX
A typical operating system has a maximum number of files that can be open at one time. The number might be variable or fixed; FOPEN_MAX
is the guaranteed minimum value of the limit.
fopen function
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 thing you can do with the value is assign it and pass it as a function argument, especially to fsetpos
.
fgetpos function, fsetpos function
Formatted output
int fprintf(FILE* stream, const char* format, ...)
The fprintf
function prints 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 has the following format (which must appear in the following order):
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 | Output 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 |
*
), in which case the field width is obtained from the next argument to be processed..
) followed by a number or an asterisk.h
, l
, or L
. The h
size means an integer is short
or unsigned
short
. The l
size means an integer is long
or unsigned
long
, a character is wint_t
, or a string is a pointer to wchar_t
. The L
size means a floating point number is long
double
.d
, i
o
u
x
, X
x
prints digits 10-15 in lowercase, and X
prints in uppercasef
e
, E
e
or E
, matching the conversion characterg
, G
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 characterc
unsigned
char
promoted to int
, or if the l
modifier is used, the argument must be wchar_t
promoted to wint_t
, which is printed as a multibyte characters
l
modifier is used, the argument must be a pointer to a wchar_t
array, which is converted to a series of multibyte charactersp
void
. The output format is implementation-defined.n
fprintf
stores in the integer the number of characters written so far. The h
or l
size modifiers can be used if the argument is a pointer to short
int
or long
int
.%
%
.fscanf function, printf function, sprintf function, vfprintf function, wcrtomb in <cwchar>, fwprintf in <cwchar>
Prints a character
int fputc(int c, FILE* stream)
The fputc
function prints 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.
putc macro, fwputc in <cwchar>
Prints a string
int fputs(const char* s, FILE* stream)
The fputs
function prints the strings s
to stream
. It returns EOF
for an error or any nonnegative value for success.
fputc function, puts function, fwputs in <cwchar>
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
, where each element is size
bytes long, into the memory pointed to by ptr
. It returns the number of elements that were read successfully.
fwrite 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 calling fopen
. 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
.
fclose function, fopen function
Formatted read
int fscanf(FILE* stream, const char* format, ...)
The fscanf
function performs a formatted read from stream
. The format
parameter contains the formatting information, and the remaining arguments are are pointers. When fscanf
reads items, it stores the values in successive arguments. 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 white space characters, non-white space characters, and conversion specifications, which begin with a percent sign (%
). A white space character directs fscanf
to skip over white space in the input stream. Non-white space characters must match the input text. Each conversion specification has the following format (which must appear in the following order):
*
) directs fscanf
to read and parse the input according to the conversion specification, but not to assign the value to an argument.h
, l
, or L
. The h
size means an integer is short
or unsigned
short
. The l
size means an integer is long
or unsigned
long
, or a string argument is a pointer to wchar_t
for the c
, s
, and [
conversion specifiers. The L
size means a floating point number is long
double
.d
i
0x
or 0X
for hexadecimal, 0
for octal, or anything else for decimalo
u
x
, X
e
, E
, f
, g
, G
c
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 appendeds
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.p
fprintf
uses.n
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 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.%
%
.fprintf function, scanf function, sscanf function, vfscanf function, mbrtowc in <cwchar>, fwscanf in <cwchar>
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 files, that is, files where a position does not necessarily fit in a long int.
The return value is zero for success or non-zero for an error.
fsetpos function, ftell function, SEEK_CUR macro, SEEK_END macro, SEEK_SET macro
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
.
fseek function, fgetpos function
Returns current file position
long int ftell(FILE* stream)
The ftell
function returns the current file position in steam. This position can be used (with an origin of SEEK_SET
) in a subsequent call to fseek
. If ftell
fails, it returns -1L
(which is not necessarily the same value as EOF
).
fgetpos function, fseek 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
, where each element is size
bytes long, and ptr
points to the first such element.
The return value is the number of complete elements successfully written to stream
.
fread function
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.
fgetc function, putc macro
Reads a character from stdin
int getchar()
The getchar
macro is equivalent to getc(stdin)
.
fgetc function, getc macro, putchar macro
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.
fgets function, getchar macro
Length of temporary file name
int L_tmpnam
L_tmpname
is the length of a temporary file name template for tmpnam
.
tmpnam function
NULL pointer
#define NULL 0
The NULL
macro expands to the integer 0, which represents a null pointer.
NULL in <cstddef>
Prints error message
void perror(const char* s)
The perror
function prints 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 the same text as that returned by strerror
, passing errno
as its argument.
strerror function in <cstdlib>
Formatted output
int printf(const char* format, ...)
The printf
function is equivalent to calling fprintf
to stdout
. See fprintf
for information about the format
string.
fprintf function, vprintf function, wprintf in <cwchar>
Prints a character
int putc(int c, FILE* stream)
The putc
macro prints the character c
, which must be cast to unsigned
char
, to stream
.
fputc function, putchar macrom wputc in <cwchar>
Prints a character to stdout
int putchar(int c)
The putchar
macro is equivalent to putc(c,
stdout)
.
fputc function, putc macro, wputchar in <cwchar>
Prints a string
int puts(const char* s)
The puts
function prints a string to stdout
.
fputs function, putc function, wputs in <cwchar>
Deletes a file
int remove(const char* filename)
The remove
function deletes the file whose name is given by filename
. It returns zero for success or non-zero for an error.
rename function
Renames a file
int rename(const char* oldname, const char* newname)
The rename
function renames the file from oldname
to newname
. The return value is zero for success or non-zero for failure.
remove function
Resets file position
void rewind(FILE* stream)
The rewind
function is equivalent to fseek(stream,
0,
SEEK_SET)
.
fseek function, fsetpos function
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 values seek toward the end of the file, and negative values seek toward the beginning of the file.
fseek function
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 value seek past the end of the file, and negative values seek toward the beginning of the file.
fseek function
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.
fseek 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.
BUFSIZ macro, setvbuf function
Set 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 NULL
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
.
_IOFBF macro, _IOLBF macro, _IONBF macro, setbuf function
Size type
typedef ... size_t;
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.
size_t in <cstddef>
Formatted print to a string
int sprintf(char* s, const char* format, ...)
The sprintf
function is like fprintf
, but instead of printing to an open file, it "prints" by copying characters to the string s
. See fprintf
for a description of the format
parameter.
fprintf function, sscanf function, vsprintf function, wsprintf in <cwchar>
Formatted read from a string
int sscanf(const char* s, const char* format, ...)
The sscanf
function is like fscanf
, but instead of reading from an open file, it "reads" characters from the string s
. See fscanf
for a description of the format
parameter.
fscanf function, sprintf function, vsscanf function, swscanf in <cwchar>
Standard error file
FILE* stderr
The stderr
macro is a standard file, suitable for printing error messages. It is not fully buffered, but might be unbuffered or line buffered.
cerr in <iostream>, clog in <iostream>
Standard input file
FILE* stdin
The stdin
macro is a standard file, suitable for reading from the program's standard input. It is fully buffered if the standard input is not an interactive device.
cin in <iostream>
Standard output file
FILE* stdout
The stdout
macro is a standard file, suitable for printing the program's standard output. It is fully buffered if the standard output is not an interactive device.
cout in <iostream>
Largest tmpnam temporary file name
const int TMP_MAX
The TMP_MAX
macro is the number of unique names the tmpnam
function generates.
function
Opens a temporary file
FILE* tmpfile()
The tmpfile
function generates a unique file name and opens the file using mode "wb+"
. When the program terminates normally, the file is automatically deleted. If the temporary file cannot be created, NULL
is returned.
tmpnam function
Returns a temporary file name
char* tmpnam(char* s)
The tmpnam
function generates a unique file name and returns a pointer to that name. If the s
parameter is not NULL
, it must point to an array of at least L_tmpnam
characters, and the new file name is copied into that array.
tmpfile function
Pushes a character back for reading later
int ungetc(int c, FILE* stream)
The ungetc
function pushes back the character c
(which must be an unsigned
char
), so the next read from stream
will return c
. Only one character of push back is guaranteed, although more than one character might work.
The return value is c
or EOF
for an error.
fgetc function, getc macro, getchar macro, ungetwc in <cwchar>
Formatted output
#include <cstdarg> int vfprintf(FILE* stream, const char* format, va_list arg)
The vfprintf
function is like fprintf
, but the arguments are taken from successive arguments in arg
(obtained by calling va_arg(arg)
). Use vfprintf
to write your own fprintf
-like function.
fprintf function, vfwprintf in <cwchar>, <stdarg>
Formatted output
#include <cstdarg> int vprintf(const char* format, va_list arg)
The vprintf
function is like printf
, but the arguments are taken from successive arguments in arg
(obtained by calling va_arg(arg)
). Use vprintf
to write your own printf
-like function.
printf function, vwprintf in <cwchar>, <stdarg>
Formatted output to a string
#include <cstdarg> int vsprintf(char* s, const char* format, va_list arg)
The vsprintf
function is like sprintf
, but the arguments are taken from successive arguments in arg
(obtained by calling va_arg(arg)
). Use vsprintf
to write your own sprintf
-like function.
sprintf function, vswprintf in <cwchar>, <stdarg>