Standard Input/Output Functions
Predefined Types and Values - FILE
, EOF
, NULL
and size_t
FILE
is a datatype which holds information about an open
file.
EOF
is a value returned to indicate end-of-file
(though is not used exclusively for that purpose) and
is required by ANSI C to be a negative integral constant
expression and is traditionally set to -1
.
NULL
is set to the value of the null pointer constant
0
BUFSIZ
is an integer constant which specifies an "appropriate"
size for file I/O buffers.
size_t
is an unsigned integral type which is large enough
to hold any value returned by sizeof
Preopened File Streams - stdin
, stdout
,
and stderr
FILE *stdin
stdin
is associated with a user's standard input stream.
FILE *stdout
stdin
is associated with an output stream used for normal
program output.
FILE *stderr
stdin
is associated with an output stream used for error
messages.
Open File - fopen
and freopen
FILE *fopen(const char *path, const char *mode)
fopen
opens the file designated by the character
string path
and associates it with a stream.
The mode
string should begin with one of the following sequences:
r
- open an existing file for reading, starting at the
beginning of the file.
w
- truncate an existing file to zero length or create a text
file for writing, starting at the beginning of the file.
a
- open or create for writing at end of text file.
r+
- open an existing file for reading and writing, starting
at the beginning of the file.
w+
- truncate an existing file to zero length or
create a text file for reading and writing, starting at the beginning of
the file.
a+
- open for reading and writing at end of file or create for reading and writing.
- The
mode
string may include a b
as either
the second or third character to indicate a binary file.
- The
mode
string may also contain other characters after
the above modes, which are used in an implementation-defined manner.
- If a file is opened for update (the
+
mode), an output
operation may not be followed by an input operation without flushing the
buffer (fflush()
)) or
repositioning (fseek()
, fsetpos
, rewind
),
and an input operation may
not be followed by an output operation without flushing the buffer or
repositioning unless the input operation has reached end-of-file.
- If
fopen
succeeds, a FILE
pointer is returned.
Otherwise, NULL
is returned and errno
is set.
FILE *freopen(const char *pathname, const char *mode, FILE *stream)
freopen
behaves exactly like fopen
except that
it associates the newly opened file with stream
rather than
creating a new stream.
freopen
is primarily used to associate a new file with
one of the standard text streams (stdin
, stdout
,
or stderr
).
Flush File Buffer - fflush
int fflush(FILE *stream)
fflush
forces any buffered output to be written,
but does not close the stream.
- If
stream
is a null pointer, fflush
flushes
all of a process' open output streams (at least on UNIX systems)
- If the operation succeeds,
fflush
returns 0.
Otherwise, EOF
is returned and errno
is set.
Close File - fclose
int fclose(FILE *stream)
fclose
causes any buffered output to be written
(possibly using fflush
)
and then closes the stream.
- Subsequent attempts to use
stream
in any routine
other than freopen
will result in errors.
- If the operation succeeds,
fclose
returns 0.
Otherwise, EOF
is returned and errno
is set.
Check or Clear File Status - feof
, ferror
and clearerr
int feof(FILE *stream)
feof
checks the end-of-file indicator for
stream
and returns non-zero if it is set.
- Note that even if the last character in a file has been read, an
end-of-file condition does not exist until a request is made to read
the character after the last character.
int ferror(FILE *stream)
ferror
checks the error indicator for
stream
and returns non-zero if it is set.
void clearerr(FILE *stream)
clearerr
clears the end-of-file and error indicators
for stream
.
- Once an end-of-file or error indicator has been set, it is not reset
until
clearerr
is called (with the exception that file
repositioning functions clear the end-of-file indicator.)
Read Character from File - getc
, fgetc
and getchar
int fgetc(FILE *stream)
fgetc
reads the next available character
from the input stream stream
and
returns it as an int
int getc(FILE *stream)
getc
is identical in function to fgetc
but
is usually implemented as a macro (which means that stream
may be evaluated more than once, so it should not be an expression with
side effects.)
int getchar(void)
getchar
reads the next available character from
stdin
and is typically implemented as getc(stdin)
(which means it is a macro with all the problems of getc
.)
- Errors and End-Of-File
- If
stream
or stdin
is at end-of-file or a
read error occurs, these routines return EOF
(and errno
is set if an error occurs.)
feof
or ferror
must therefore be used to
distinguish between the two conditions.
Write Character to File - putc
, fputc
and putchar
int fputc(int c, FILE *stream)
fputc
writes c
to the output stream
stream
as an
unsigned char
and returns the character as an int
.
If an error occurs, EOF
is returned and errno
is set.
int putc(int c, FILE *stream)
putc
is identical in function to fputc
but
is usually implemented as a macro (which means that stream
and c
may be evaluated more than once, so they should not be expressions with
side effects.)
int putchar(int c)
putchar
writes c
to stdout
and is typically implemented as putc(stdout)
(which means it is a macro with all the problems of putc
.)
Push Character Back into Buffer - ungetc
int ungetc(int c, FILE *stream)
ungetc
pushes c
back onto the input stream
stream
, so that it will be returned by a subsequent read
of stream
.
- Pushed back characters are read in reverse order.
- If a file repositioning function
(
fseek()
, fsetpos
, rewind
) is
used, any pushed back characters are lost.
ungetc
does not affect the contents of the file pointed
to by stream
- One character of pushback is guaranteed.
- Attempts to push
EOF
have no effect on stream
and return EOF
Read String from File - fgets
and gets
char *fgets(char *s, int n, FILE *stream)
fgets
reads characters from stream
and stores
them in the string pointed to by s
.
- Reading stops when a newline character is seen, end-of-file is reached
or
n-1
characters have been read, and
'\0'
is appended to s
(after any newline character.)
- If end-of-file occurs before any characters have been read,
fgets
returns NULL
and the contents of s
are unchanged.
- If an error occurs at any time during the read operation,
fgets
returns NULL
and the contents of s
are undefined.
- Otherwise,
fgets
returns s
char *gets(char *s, FILE *stream)
gets
is similar to fgets
,
but is much more dangerous.
gets
does not store a newline character.
- More importantly,
gets
assumes that s
is infinitely long, allowing sufficiently knowledgeable programmers
to worm their way inside the program.
Write String to File - fputs
and puts
int fputs(const char *s, FILE *stream)
fputs
writes the null-terminated string s
to the output stream stream
.
- If an error occurs,
fputs
returns EOF
.
Otherwise, is returns a nonnegative integer.
int puts(const char *s)
puts
writes the null-terminated string s
,
followed by a newline character,
to the stdout
output stream.
Read Binary Data from File - fread
size_t fread(void *ptr, size_t siz, size_t num, FILE *stream)
fread
reads up to num
objects,
each siz
bytes long, from input stream stream
,
storing them in the memory pointed to by ptr
.
- The number of objects read is returned.
- If an error occurs, zero will be returned.
- If end-of-file is reached,
the value returned will be less than
num
(and may be zero,
in which case feof
or ferror
should be used to
distinguish between the two conditions.)
Write Binary Data to File - fwrite
size_t fwrite(const void *ptr, size_t siz, size_t num, FILE *stream)
fwrite
writes up to num
objects,
each siz
bytes long, from
the memory pointed to by ptr
to the output stream stream
.
- The number of objects written is returned.
- If an error occurs, zero will be returned.
Read Formatted Input - scanf
, fscanf
, sscanf
int scanf(const char *format, ...)
int fscanf(FILE *stream, const char *format, ...)
int sscanf(const char *str, const char *format, ...)
Write Formatted Output - printf
, fprintf
, sprintf
int printf(const char *format, ...)
int fprintf(FILE *stream, const char *format, ...)
fprintf
writes to output stream stream
.
-
int sprintf(const char *str, const char *format, ...)
sprintf
"writes" its output to the character string
str
(followed by a terminating '\0'
.)
- All three functions return the number of characters written (not
including the terminating
'\0'
for sprintf
)
File Position - fgetpos
, fsetpos
,
rewind
, fseek
, and ftell
int fgetpos(FILE *stream, fpos_t *pos);
fgetpos
stores
the value of the current file position indicator for stream
in pos
.
pos
is an implementation-defined type which
may be integral or may be a complex structure.
- If an error occurs, a non-zero value is returned and
errno
is set.
int fsetpos(FILE *stream, fpos_t *pos)
fsetpos
sets the file position indicator for
stream
to the position indicated by pos
.
- If an error occurs, a non-zero value is returned and
errno
is set.
- If
fsetpos
succeeds, the end-of-file indicator is cleared.
void rewind(FILE *stream)
rewind
sets the file position indicator for
stream
to the beginning of the file.
int fseek(FILE *stream, long offset, int whence)
fseek
sets the file position indicator for stream
.
The new byte position is obtained by adding offset
to
the position specified by whence
:
- If
whence
is set to SEEK_CUR, the offset
is computed from the current position in the file.
- If
whence
is set to SEEK_SET, the offset
is computed from the beginning of the file.
- If
whence
is set to SEEK_END, the offset
is computed from the end of the file.
- SEEK_CUR, SEEK_SET, and
SEEK_END are all defined in <stdio.h>.
fseek
is usually applied to binary files.
long ftell(FILE *stream)
ftell
returns the current file position for
stream
.
- For binary files, the value returned is the number of bytes from the
beginning of the file to the current file position.
- For text files, the value is implementation-defined, but is guaranteed
to be useable in
fseek
and 0L
must represent
the beginning of the file.
Alter File Buffer Size - setbuf
and setvbuf
void setvbuf(FILE *stream, char *buf, int buftype, size_t bufsize)
setvbuf
sets the type, size and location of the buffer
for stream
.
- The three types of buffering available are:
- _IOFBF causes I/O to be block buffered, meaning
that bytes are saved up and written when
bufsize
has been
reached.
- _IOLBF causes I/O to be line buffered, meaning
that the buffer is written when either a newline character is saved to
the buffer or when
bufsize
has been reached.
- _IONBF means that no buffering is done; everything
is immediately written.
- If
buf
is non-null, it is assumed to be at least
bufsize
bytes long and will be used instead of the
automatically created buffer.
- The predefined constant BUFSIZ is the recommended
value for the buffer size.
- If
buf
is NULL
,
the stream is completely unbuffered.
setvbuf
can safely be called after a stream has been
opened but before any data are read or written.
setvbuf
returns EOF
on error.
void setbuf(FILE *stream, char *buf)
setbuf
has the same effect as
setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
Temporary File Functions - tmpfile
and tmpnam
FILE *tmpfile(void)
tmpfile
attempts to create a new file and open it
using mode wb+
.
- If the create and open succeed, a
FILE
pointer is
returned.
- If the file could not be opened,
NULL
is returned.
- The file is automatically deleted when it is closed or when
the process terminates.
- Note that this function may create a file which is publicly readable and
writable.
char *tmpnam(char *str)
tmpnam
generates a temporary file name
which was not in use when tmpnam
was called.
- If
str
is non-null, the file name is copied to that buffer.
str
is expected to be at least
L_tmpnam
characters long.
- If
str
is null, a static buffer is used, meaning that
subsequent calls to tmpnam
may overwrite the buffer.
- Temporary file names use the path prefix
P_tmpdir
.
- Both
L_tmpnam
and P_tmpdir
are
defined in <stdio.h>.
tmpnam
is guaranteed to be able to generate at least
TMP_MAX unique temporary file names, where
TMP_MAX must be at least 25.
- Note that there is a race condition between file name selection
and file creation.
- Note also that
tmpnam
does not create the file and therefore
does not ensure the file will be deleted after the program is terminated.
Previous,
Next,
Index