9.11 Standard Input/Output (<stdio.h>)

The <stdio.h> header file declares three types, several macros, and many functions for performing text input and output. A text stream consists of a sequence of lines; each line ends with a new-line character.

Types

size_t


An unsigned integral type of the result of the sizeof operator.

FILE


An object type capable of recording all the information needed to control a data stream, including its file-position indicator, a pointer to its associated buffer (if any), an error indicator that records whether a read/write error occurred, and an end-of-file indicator that records whether the end of the file has been reached.

fpos_t


An object capable of recording all the information needed to uniquely specify every position within a file.

Macros

NULL


Expands to an implementation-defined null pointer constant.

_IOFBF _IOLBF _IONBF


Expand to integral constant expressions with distinct values, suitable for use as the third argument to the setvbuf function.

BUFFSIZ


Expands to an integral constant expression, which is the size of the buffer used by the setbuf function.

EOF


Expands to a negative integral constant expression that is returned by several functions to indicate end-of-file.

FOPEN_MAX


Expands to an integral constant expression that is the minimum number of files that the DEC C compiler for your system guarantees can be open simultaneously.

FILENAME_MAX


Expands to an integral constant expression that is the size needed for an array of char large enough to hold the longest file name string that the DEC C compiler for your system guarantees can be opened.

L_tmpnam


Expands to an integral constant expression that is the size needed for an array of char large enough to hold a temporary file name string generated by the tmpnam function.

SEEK_CUR SEEK_END SEEK_SET


Expand to integral constant expressions with distinct values; suitable for use as the third argument to the fseek function.

TMP_MAX


Expands to an integral constant expression that is the minimum number of unique file names that can be generated by the tmpnam function.

stderr stdin stdout


Expressions of type pointer to FILE that point to the FILE objects associated, respectively, with the standard error, input, and output streams.

File Operation Functions

int remove(const char *filename);


Makes the file whose name is pointed to by filename no longer accessible by that name. Any subsequent attempt to open that file using that name will fail. The remove function returns 0 if the operation succeeds, nonzero if it fails. If the file is open, the behavior of this function is implementation-defined.

int rename(const char *old, const char *new);


Renames the file from the name pointed to by old to the name pointed to by new. The file is no longer accessible by the old name. The rename function returns 0 if the operation succeeds, nonzero if it fails (in which case the file, if it existed, is still known by its original name). If the new file exists before rename is called, the behavior of this function is implementation- defined.

FILE *tmpfile(void);


Creates a temporary binary file that is automatically removed when it is closed or when program execution ends. If execution ends abnormally, whether an open temporary file is removed is implementation-dependent. The file is opened for update with wb+ mode (see Table 9-1). The tmpfile function returns a pointer to the stream of the file that it created. If the file cannot be created, tmpfile returns a null pointer.

FILE *tmpnam(void);


Generates a valid file name that is different than the name of an existing file. Each call to tmpnam , up to TMP_MAX times, generates a different name. If tmpnam is called more than TMP_MAX times, the behavior is implementation-defined.

If the argument is a null pointer, the tmpnam function leaves its result in an internal static object and returns a pointer to that object. Subsequent calls to tmpnam can modify the same object. If the argument is not a null pointer, it is assumed to point to an array of at least L_tmpnam chars . The tmpnam function writes its result into that array and returns the argument as its value.

File Access Functions

int fclose(FILE *stream);


Flushes the stream pointed to by stream and closes the associated file. Any unwritten buffered data for the stream is delivered to the host environment to be written to the file. Any unread buffered data is discarded. The stream is disassociated from the file. If the associated buffer was automatically allocated, it is deallocated. The fclose function returns 0 if the stream was successfully closed, or it returns EOF if any errors are detected.

int fflush(FILE *stream);


If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function delivers any unwritten data to the host environment to be written to the file. Otherwise, the behavior is undefined. If stream is a null pointer, fflush flushes all output or update streams in which the most recent operation was not input. The fflush function returns 0 if the operation is successful, or it returns EOF if a write error occurs.

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


Opens the file pointed to by filename and associates a stream with it. The argument mode points to a string beginning with one of the character sequences listed in Table 9-1. Additional characters can follow these sequences.

Table 9-1 File Modes

Mode  Description 
r   open text file for reading 
w   truncate to zero length or create text file for writing 
a   append; open or create text file for writing at end-of-file 
rb   open binary file for reading 
wb   truncate to zero length or create binary file for writing 
ab   append; open or create binary file for writing at end-of-file 
r+   open text file for update (reading and writing) 
w+   truncate to zero length or create text file for update 
a+   append; open or create text file for update, writing at end-of-file 
r+b or rb+   open binary file for update (reading and writing) 
w+b or wb+   truncate to zero length or create binary file for update 
a+b or ab+   append; open or create binary file for update, writing at end-of-file 

The fopen function returns a pointer to the object controlling the stream. If the open operation fails, fopen returns a null pointer.

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


Opens the file pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used in the same way as with the fopen function. The freopen function first tries to close any file associated with the specified stream. Failure to close the file successfully is ignored. The error and end-of-file indicators for the stream are cleared.

The primary use of freopen is to change the file associated with a standard text stream (stderr , stdin , or stdout ), because those identifiers need not be modifiable lvalues to which the value returned by the fopen function can be assigned.

The freopen function returns a pointer to the object controlling the stream. If the open operation fails, freopen returns a null pointer.

void setbuf(FILE *stream, char *buf);


Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer) with the value _IONBF for mode.

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


Associates a buffer with an input or an output file. The setvbuf function can be used only after the stream pointed to by stream has been associated with an open file and before any other operation is performed on the stream. The argument mode determines how stream is to be buffered:

If buf is not a null pointer, the array it points to can be used instead of a buffer allocated by the setvbuf function. The size of the array is specified by size. The contents of the array at any time are indeterminate. The setvbuf function returns 0 if successful, or nonzero if an invalid value is specified for mode or if the request cannot be honored.

Formatted Input/Output Functions

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


Writes output to the stream pointed to by stream, under control of the string pointed to by format, which specifies how subsequent arguments are converted for output. If there are an insufficient number of arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored. The fprintf function returns when the end of the format string is encountered. The fprintf function returns the number of characters transmitted, or it returns a negative value if an output error occurred.

See your DEC C library routine documentation for more information.

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


Reads input from the stream pointed to by stream, under control of the string pointed to by format, which specifies the allowable input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are an insufficient number of arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored.

The fscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, fscanf returns the number of input items assigned, which can be fewer than provided for, or even 0, if there is an early matching failure.

See your DEC C library routine documentation for more information.

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


Equivalent to the fprintf function except that printf writes formatted output to the standard output stream (stdout ).

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


Equivalent to the fscanf function except that scanf reads formatted input from the standard input stream (stdin ).

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


Equivalent to the fprintf function except that the argument s specifies an array, rather than a stream, into which the generated output will be written. A null character is written at the end of the characters written. If copying takes place between objects that overlap, the behavior is undefined. The sprintf function returns the number of characters written into the array, not counting the terminating null character.

int sscanf(const char *s, const char *format, ...);


Equivalent to the fscanf function except that the argument s specifies a string, rather than a stream, from which the input will be read. Reaching the end of the string is equivalent to the fscanf function encountering end-of-file. If copying takes place between objects that overlap, the behavior is undefined.

#include <stdarg.h> int vfprintf(FILE *stream, const char *format, va_list arg);


Equivalent to the fprintf function with the variable argument list replaced by arg, which must have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfprintf function does not invoke the va_end macro.

#include <stdarg.h> int vprintf(const char *format, va_list arg);


Equivalent to the printf function with the variable argument list replaced by arg, which must have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vprintf function does not invoke the va_end macro.

#include <stdarg.h> int vsprintf(char *s, const char *format, va_list arg);


Equivalent to the sprintf function with the variable argument list replaced by arg, which must have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsprintf function does not invoke the va_end macro.

Character Input/Output Functions

int fgetc(FILE *stream);


Returns the next character (if there is one) as an unsigned char converted to an int , from the input stream pointed to by stream, and advances the associated file-position indicator for the stream (if defined). If the stream is at end-of-file, the end-of-file indicator for the stream is set, and fgetc returns EOF . If a read error occurs, the error indicator is set, and fgetc returns EOF .

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


Reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after the end-of-file. A null character is written immediately after the last character read into the array.

The fgets function returns s if successful. If the end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.

int fputc(int c, FILE *stream);


Writes the character c (converted to an unsigned char ) to the output stream pointed to by stream, at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream. The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set, and fputc returns EOF .

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


Writes the string pointed to by s to the stream pointed to by stream. The terminating null character is not written.

The fputs function returns EOF if a write error occurs. Otherwise, it returns a nonnegative value.

int getc(FILE *stream);


Equivalent to the fgetc function, but if it is implemented as a macro it can evaluate stream more than once. For this reason, the argument should never be an expression with side effects.

int getchar(void);


Equivalent to the getc function with the argument stdin .

char *gets(char *s);


Reads characters from the input stream pointed to by stdin into the array pointed to by s, until the end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

The fgets function returns s if successful. If the end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.

int putc(int c, FILE *stream);


Equivalent to the fputc function, but if it is implemented as a macro it can evaluate stream more than once. For this reason the argument should never be an expression with side effects.

int putchar(int c);


Equivalent to the putc function with the second argument stdout .

int puts(const char s);


Writes the string pointed to by s to the stream pointed to by stdout , and appends a new-line character to the output. The terminating null character is not written. The puts function returns EOF if a write error occurs. Otherwise, it returns a nonnegative value.

int ungetc(int c, FILE *stream);


Pushes a character c (converted to an unsigned char ) back into the input stream pointed to by stream, and leaves the stream positioned before the character. The pushed back characters are returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call to a file positioning function for that stream (fseek , fsetpos , or rewind ) discards any pushed-back characters.

One pushback is guaranteed, even if there has been no previous activity on the file. The ungetc function returns the converted pushed-back character, or it returns EOF if the operation fails.

Direct Input/Output Functions

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);


Reads into the array pointed to by ptr up to nmemb elements of size size from the stream pointed to by stream. The file-position indicator for the stream (if defined) is advanced by the number of characters successfully read. If an error occurs, the resulting value of the file-position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.

The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered. If size or nmemb is 0, fread returns 0, and the contents of the array and the state of the stream are unchanged.

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


Writes from the array pointed to by ptr up to nmemb elements of size size to the stream pointed to by stream. The file-position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file-position indicator for the stream is indeterminate.

The fwrite function returns the number of elements successfully written, which is less than nmemb only if a write error is encountered.

File Positioning Functions

int fgetpos(FILE *stream, fpos_t *pos);


Stores the current value of the file-position indicator for the stream pointed to by stream into the object pointed to by pos. The value stored contains unspecified information used by the fsetpos function to return the stream to its position at the time of the call to fgetpos .

If successful, the fgetpos function returns 0. On failure, fgetpos returns nonzero and stores an implementation-defined positive value in errno .

int fseek(FILE *stream, long int offset, int whence);


Sets the file-position indicator to the specified byte offset in the stream pointed to by stream.

For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence, which is one of the following:

For a text stream, either offset is 0 or it is a value returned by an earlier call to the ftell function on the same stream and whence is SEEK_SET .

A successful call to fseek clears the end-of- file indicator for the stream and reverses any effects of the ungetc function on the same stream. After an fseek call, the next operation on an update stream can be either input or output. The fseek function returns nonzero only for a request that cannot be satisfied.

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


Sets the file-position indicator for the stream pointed to by stream according to the value of the object pointed to by pos, which is a value obtained from an earlier call to the fgetpos function on the same stream.

A successful call to fsetpos clears the end-of- file indicator for the stream and reverses any effects of the ungetc function on the same stream. After an fsetpos call, the next operation on an update stream can be either input or output.

If successful, the fsetpos function returns 0. On failure, fsetpos returns nonzero and stores an implementation-defined positive value in errno .

long int ftell(FILE *stream);


Gets the current value of the file-position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file-position indicator contains unspecified information used by the fseek function for returning the file-position indicator for the stream to its position at the time of the call to ftell . The difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

If successful, the ftell function returns the current value of the file-position indicator for the stream. On failure, ftell returns -1L and stores an implementation-defined positive value in errno .

void rewind(FILE *stream);


Sets the file-position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to the following, except that the error indicator for the stream is also cleared:
(void)fseek(stream, 0L, SEEK_SET)

The rewind function returns no value.

Error-Handling Functions

void clearerr(FILE *stream);


Clears the end-of-file and error indicators for the stream pointed to by stream. The clearerr function returns no value.

int feof(FILE *stream);


Tests the end-of-file indicator for the stream pointed to by stream. The feof function returns nonzero only if the end-of-file indicator is set for stream .

int ferror(FILE *stream);


Tests the error indicator for the stream pointed to by stream. The ferror function returns nonzero only if the end-of-file indicator is set for stream .

void perror(const char *s);


Maps the error number in the integer expression errno to an error message. It writes the following sequence of characters to the standard error stream:

  1. The string pointed to by s followed by a colon (:) and a space (if s is not a null pointer and the character pointed to by s is not the null character)

  2. An appropriate error message string followed by a new- line character

The contents of the error message strings are the same as those returned by the strerror function with argument errno , which are implementation-defined. The perror function returns no value.


Previous Page | Next Page | Table of Contents | Index