C++ Programming/Code/Standard C Library/IO

From Wikibooks, open books for an open world
Jump to: navigation, search

Standard C I/O[edit]

The Standard C Library includes routines that are somewhat outdated, but due to the history of the C++ language and its objective to maintain compatibility these are included in the package.

C I/O calls still appear in old code (not only ANSI C 89 but even old C++ code). Its use today may depend on a large number of factors, the age of the code base or the level of complexity of the project or even based on the experience of the programmers. Why use something you are not familiar with if you are proficient in C and in some cases C-style I/O routines are superior to their C++ I/O counterparts, for instance they are more compact and may be are good enough for the simple projects that don't make use of classes.

Note:
If you're learning I/O for the first time you probably should program using the C++ I/O system and not bring legacy I/O systems into the mix. Learn C-style I/O only if you have to.

clearerr[edit]

Syntax
#include <cstdio>
void clearerr( FILE *stream );

The clearerr function resets the error flags and EOF indicator for the given stream. If an error occurs, you can use perror() or strerror() to figure out which error actually occurred, or read the error from the global variable errno.

Related topics
feof - ferror - perror - strerror

fclose[edit]

Syntax
#include <cstdio>
int fclose( FILE *stream );

The function fclose() closes the given file stream, deallocating any buffers associated with that stream. fclose() returns 0 upon success, and EOF otherwise.

Related topics
fflush - fopen - freopen - setbuf

feof[edit]

Syntax
#include <cstdio>
int feof( FILE *stream );

The function feof() returns TRUE if the end-of-file was reached, or FALSE otherwise.

Related topics
clearerr - ferror - getc - perror - putc

ferror[edit]

Syntax
#include <cstdio>
int ferror( FILE *stream );

The ferror() function looks for errors with stream, returning zero if no errors have occurred, and non-zero if there is an error. In case of an error, use perror() to determine which error has occurred.

Related topics
clearerr - feof - perror

fflush[edit]

Syntax
#include <cstdio>
int fflush( FILE *stream );

If the given file stream is an output stream, then fflush() causes the output buffer to be written to the file. If the given stream is of the input type, the behavior of fflush() depends on the library being used (for example, some libraries ignore the operation, others report an error, and others clear pending input).

fflush() is useful when either debugging (for example, if a program segfaults before the buffer is sent to the screen), or it can be used to ensure a partial display of output before a long processing period.

By default, most implementations have stdout transmit the buffer at the end of each line, while stderr is flushed whenever there is output. This behavior changes if there is a redirection or pipe, where calling fflush(stdout) can help maintain the flow of output.

printf( "Before first call\n" );
fflush( stdout );
shady_function();
printf( "Before second call\n" );
fflush( stdout );
dangerous_dereference();
Related topics
fclose - fopen - fread - fwrite - getc - putc

fgetc[edit]

Syntax
#include <cstdio>
int fgetc( FILE *stream );

The fgetc() function returns the next character from stream, or EOF if the end of file is reached or if there is an error.

Related topics
fopen - fputc - fread - fwrite - getc - getchar - gets - putc

fgetpos[edit]

Syntax
#include <cstdio>
int fgetpos( FILE *stream, fpos_t *position );

The fgetpos() function stores the file position indicator of the given file stream in the given position variable. The position variable is of type fpos_t (which is defined in cstdio) and is an object that can hold every possible position in a FILE. fgetpos() returns zero upon success, and a non-zero value upon failure.

Related topics
fseek - fsetpos - ftell

fgets[edit]

Syntax
#include <cstdio>
char *fgets( char *str, int num, FILE *stream );

The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str. The string that fgets() produces is always null-terminated. fgets() will stop when it reaches the end of a line, in which case str will contain that newline character. Otherwise, fgets() will stop when it reaches num - 1 characters or encounters the EOF character. fgets() returns str on success, and NULL on an error.

Related topics
fputs - fscanf - gets - scanf

fopen[edit]

Syntax
#include <cstdio>
FILE *fopen( const char *fname, const char *mode );

The fopen() function opens a file indicated by fname and returns a stream associated with that file. If there is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. for input, output, etc.)

The mode contains up to three characters. The first character is either "r", "w", or "a", which indicates how the file is opened. A file opened for reading starts allows input from the beginning of the file. For writing, the file is erased. For appending, the file is kept and writing to the file will start at the end. The second character is "b", is an optional flag that opens the file as binary - omitting any conversions from different formats of text. The third character "+" is an optional flag that allows read and write operations on the file (but the file itself is opened in the same way.

Mode Meaning Mode Meaning
"r" Open a text file for reading "r+" Open a text file for read/write
"w" Create a text file for writing "w+" Create a text file for read/write
"a" Append to a text file "a+" Open a text file for read/write
"rb" Open a binary file for reading "rb+" Open a binary file for read/write
"wb" Create a binary file for writing "wb+" Create a binary file for read/write
"ab" Append to a binary file "ab+" Open a binary file for read/write

An example:

int ch;
FILE *input = fopen( "stuff", "r" );
ch = getc( input );
Related topics
fclose - fflush - fgetc - fputc - fread - freopen - fseek - fwrite - getc - getchar - setbuf

fprintf[edit]

Syntax
#include <cstdio>
int fprintf( FILE *stream, const char *format, ... );

The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs. An example:

char name[20] = "Mary";
FILE *out;
out = fopen( "output.txt", "w" );
if( out != NULL )
  fprintf( out, "Hello %s\n", name );
Related topics
fputc - fputs - fscanf - printf - sprintf

fputc[edit]

Syntax
#include <cstdio>
int fputc( int ch, FILE *stream );

The function fputc() writes the given character ch to the given output stream. The return value is the character, unless there is an error, in which case the return value is EOF.

Related topics
fgetc - fopen - fprintf - fread - fwrite - getc - getchar - putc

fputs[edit]

Syntax
#include <cstdio>
int fputs( const char *str, FILE *stream );

The fputs() function writes an array of characters pointed to by str to the given output stream. The return value is non-negative on success, and EOF on failure.

Related topics
fgets - fprintf - fscanf - gets - getc - puts

fread[edit]

Syntax
#include <cstdio>
int fread( void *buffer, size_t size, size_t num, FILE *stream );

The function fread() reads num number of objects (where each object is size bytes) and places them into the array pointed to by buffer. The data comes from the given input stream. The return value of the function is the number of things read. You can use feof() or ferror() to figure out if an error occurs.

Related topics
fflush - fgetc - fopen - fputc - fscanf - fwrite - getc

freopen[edit]

Syntax
#include <cstdio>
FILE *freopen( const char *fname, const char *mode, FILE *stream );

The freopen() function is used to reassign an existing stream to a different file and mode. After a call to this function, the given file stream will refer to fname with access given by mode. The return value of freopen() is the new stream, or NULL if there is an error.

Related topics
fclose - fopen

fscanf[edit]

Syntax
#include <cstdio>
int fscanf( FILE *stream, const char *format, ... );

The function fscanf() reads data from the given file stream in a manner exactly like scanf(). The return value of fscanf() is the number of variables that are actually assigned values, including zero if there were no matches. EOF is returned if there was an error reading before the first match.

Related topics
fgets - fprintf - fputs - fread - fwrite - scanf - sscanf

fseek[edit]

Syntax
#include <cstdio>
int fseek( FILE *stream, long offset, int origin );

The function fseek() sets the file position data for the given stream. The origin value should have one of the following values (defined in cstdio):

Name Explanation
SEEK_SET Seek from the start of the file
SEEK_CUR Seek from the current location
SEEK_END Seek from the end of the file

fseek() returns zero upon success, non-zero on failure. You can use fseek() to move beyond a file, but not before the beginning. Using fseek() clears the EOF flag associated with that stream.

Related topics
fgetpos - fopen - fsetpos - ftell - rewind

fsetpos[edit]

Syntax
#include <cstdio>
int fsetpos( FILE *stream, const fpos_t *position );

The fsetpos() function moves the file position indicator for the given stream to a location specified by the position object. fpos_t is defined in cstdio. The return value for fsetpos() is zero upon success, non-zero on failure.

Related topics
fgetpos - fseek - ftell

ftell[edit]

Syntax
#include <cstdio>
long ftell( FILE *stream );

The ftell() function returns the current file position for stream, or -1 if an error occurs.

Related topics
fgetpos - fseek - fsetpos

fwrite[edit]

Syntax
#include <cstdio>
int fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

The fwrite() function writes, from the array buffer, count objects of size size to stream. The return value is the number of objects written.

Related topics
fflush - fgetc - fopen - fputc - fread - fscanf - getc

getc[edit]

Syntax
#include <cstdio>
int getc( FILE *stream );

The getc() function returns the next character from stream, or EOF if the end of file is reached. getc() is identical to fgetc(). For example:

int ch;
FILE *input = fopen( "stuff", "r" );             
 
ch = getc( input );
while( ch != EOF ) {
  printf( "%c", ch );
  ch = getc( input );
}
Related topics
feof - fflush - fgetc - fopen - fputc - fgetc - fread - fwrite - putc - ungetc

getchar[edit]

Syntax
#include <cstdio>
int getchar( void );

The getchar() function returns the next character from stdin, or EOF if the end of file is reached.

Related topics
fgetc - fopen - fputc - putc

gets[edit]

Syntax
#include <cstdio>
char *gets( char *str );

The gets() function reads characters from stdin and loads them into str, until a newline or EOF is reached. The newline character is translated into a null termination. The return value of gets() is the read-in string, or NULL if there is an error.

Note:
gets() does not perform bounds checking, and thus risks overrunning str. For a similar (and safer) function that includes bounds checking, see fgets().

Related topics
fgetc - fgets - fputs - puts

perror[edit]

Syntax
#include <cstdio>
void perror( const char *str );

The perror() function writes str, a ":" followed by a space, an implementation-defined and/or language-dependent error message corresponding to the global variable errno, and a newline to stderr. For example:

char* input_filename = "not_found.txt";
FILE* input = fopen( input_filename, "r" );
if( input == NULL ) {
  char error_msg[255];
  sprintf( error_msg, "Error opening file '%s'", input_filename );
  perror( error_msg );
  exit( -1 );
}

If the file called not_found.txt is not found, this code will produce the following output:

 Error opening file 'not_found.txt': No such file or directory

If "str" is a null pointer or points to the null byte, only the error message corresponding to errno and a newline are written to stderr.

Related topics
clearerr - feof - ferror

printf[edit]

Syntax
#include <cstdio>
int printf( const char *format, ... );

The printf() function prints output to stdout, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code

char name[20] = "Bob";
int age = 21;
printf( "Hello %s, you are %d years old\n", name, age );

displays the following output:

 Hello Bob, you are 21 years old

The %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot.

Control Character Explanation
 %c a single character
 %d a decimal integer
 %i an integer
 %e scientific notation, with a lowercase "e"
 %E scientific notation, with an uppercase "E"
 %f a floating-point number
 %g use %e or %f, whichever is shorter
 %G use %E or %f, whichever is shorter
 %o an octal number
 %x unsigned hexadecimal, with lowercase letters
 %X unsigned hexadecimal, with uppercase letters
 %u an unsigned integer
 %s a string
 %x a hexadecimal number
 %p a pointer
 %n the argument shall be a pointer to an integer into which is placed the number of characters written so far
 %% a percent sign

A field-length specifier may appear before the final control character to indicate the width of the field:

  • h, when inserted inside %d, causes the argument to be a short int.
  • l, when inserted inside %d, causes the argument to be a long.
  • l, when inserted inside %f, causes the argument to be a double.
  • L, when inserted inside %d or %f, causes the argument to be a long long or long double respecively.

An integer placed between a % sign and the format command acts as a minimum field width specifier, and pads the output with spaces or zeros to make it long enough. If you want to pad with zeros, place a zero before the minimum field width specifier:

  %012d

You can also include a precision modifier, in the form of a .N where N is some number, before the format command:

 %012.4d

The precision modifier has different meanings depending on the format command being used:

  • With %e, %E, and %f, the precision modifier lets you specify the number of decimal places desired. For example, %12.6f will display a floating number at least 12 digits wide, with six decimal places.
  • With %g and %G, the precision modifier determines the maximum number of significant digits displayed.
  • With %s, the precision modifier simply acts as a maximum field length, to complement the minimum field length that precedes the period.

All of printf()'s output is right-justified, unless you place a minus sign right after the % sign. For example,

 %-12.4f 

will display a floating point number with a minimum of 12 characters, 4 decimal places, and left justified. You may modify the %d, %i, %o, %u, and %x type specifiers with the letter l and the letter h to specify long and short data types (e.g. %hd means a short integer). The %e, %f, and %g type specifiers can have the letter l before them to indicate that a double follows. The %g, %f, and %e type specifiers can be preceded with the character '#' to ensure that the decimal point will be present, even if there are no decimal digits. The use of the '#' character with the %x type specifier indicates that the hexidecimal number should be printed with the '0x' prefix. The use of the '#' character with the %o type specifier indicates that the octal value should be displayed with a 0 prefix.

Inserting a plus sign '+' into the type specifier will force positive values to be preceded by a '+' sign. Putting a space character ' ' there will force positive values to be preceded by a single space character.

You can also include constant escape sequences in the output string.

The return value of printf() is the number of characters printed, or a negative number if an error occurred.

Related topics
fprintf - puts - scanf - sprintf

putc[edit]

Syntax
#include <cstdio>
int putc( int ch, FILE *stream );

The putc() function writes the character ch to stream. The return value is the character written, or EOF if there is an error. For example:

int ch;
FILE *input, *output;
input = fopen( "tmp.c", "r" );
output = fopen( "tmpCopy.c", "w" );
ch = getc( input );
while( ch != EOF ) {
  putc( ch, output );
  ch = getc( input );
}
fclose( input );
fclose( output );

Generates a copy of the file tmp.c called tmpCopy.c.

Related topics
feof - fflush - fgetc - fputc - getc - getchar - putchar - puts

putchar[edit]

Syntax
#include <cstdio>
int putchar( int ch );

The putchar() function writes ch to stdout. The code

putchar( ch );

is the same as

putc( ch, stdout );

The return value of putchar() is the written character, or EOF if there is an error.

Related topics
putc

puts[edit]

Syntax
#include <cstdio>
int puts( char *str );

The function puts() writes str to stdout. puts() returns non-negative on success, or EOF on failure.

Related topics
fputs - gets - printf - putc

remove[edit]

Syntax
#include <cstdio>
int remove( const char *fname );

The remove() function erases the file specified by fname. The return value of remove() is zero upon success, and non-zero if there is an error.

Related topics
rename

rename[edit]

Syntax
#include <cstdio>
int rename( const char *oldfname, const char *newfname );

The function rename() changes the name of the file oldfname to newfname. The return value of rename() is zero upon success, non-zero on error.

Related topics
remove

rewind[edit]

Syntax
#include <cstdio>
void rewind( FILE *stream );

The function rewind() moves the file position indicator to the beginning of the specified stream, also clearing the error and EOF flags associated with that stream.

Related topics
fseek

scanf[edit]

Syntax
#include <cstdio>
int scanf( const char *format, ... );

The scanf() function reads input from stdin, according to the given format, and stores the data in the other arguments. It works a lot like printf(). The format string consists of control characters, whitespace characters, and non-whitespace characters. The control characters are preceded by a % sign, and are as follows:

Control Character Explanation
 %c a single character
 %d a decimal integer
 %i an integer
 %e, %f, %g a floating-point number
 %lf a double
 %o an octal number
 %s a string
 %x a hexadecimal number
 %p a pointer
 %n an integer equal to the number of characters read so far
 %u an unsigned integer
 %[] a set of characters
 %% a percent sign

scanf() reads the input, matching the characters from format. When a control character is read, it puts the value in the next variable. Whitespace (tabs, spaces, etc.) are skipped. Non-whitespace characters are matched to the input, then discarded. If a number comes between the % sign and the control character, then only that many characters will be converted into the variable. If scanf() encounters a set of characters, denoted by the %[] control character, then any characters found within the brackets are read into the variable. The return value of scanf() is the number of variables that were successfully assigned values, or EOF if there is an error.

This code snippet uses scanf() to read an int, float, and a double from the user. Note that the variable arguments to scanf() are passed in by address, as denoted by the ampersand (&) preceding each variable:

int i;
float f;               
double d;
 
printf( "Enter an integer: " );
scanf( "%d", &i );             
 
printf( "Enter a float: " );
scanf( "%f", &f );             
 
printf( "Enter a double: " );
scanf( "%lf", &d );             
 
printf( "You entered %d, %f, and %f\n", i, f, d );
Related topics
fgets - fscanf - printf - sscanf

setbuf[edit]

Syntax
#include <cstdio>
void setbuf( FILE *stream, char *buffer );

The setbuf() function sets stream to use buffer, or, if buffer is NULL, turns off buffering. This function expects that the buffer be BUFSIZ characters long - since this function does not support specifying the size of the buffer, buffers larger than BUFSIZ will be partly unused.

Related topics
fclose - fopen - setvbuf

setvbuf[edit]

Syntax
#include <cstdio>
int setvbuf( FILE *stream, char *buffer, int mode, size_t size );

The function setvbuf() sets the buffer for stream to be buffer, with a size of size. mode can be one of:

  • _IOFBF, which indicates full buffering
  • _IOLBF, which means line buffering
  • _IONBF, which means no buffering
Related topics
fflush - setbuf

sprintf[edit]

Syntax
#include <cstdio>
int sprintf( char *buffer, const char *format, ... );

The sprintf() function is just like printf(), except that the output is sent to buffer. The return value is the number of characters written. For example:

char string[50];
int file_number = 0;         
 
sprintf( string, "file.%d", file_number );
file_number++;
output_file = fopen( string, "w" );

Note that sprintf() does the opposite of a function like atoi() -- where atoi() converts a string into a number, sprintf() can be used to convert a number into a string.

For example, the following code uses sprintf() to convert an integer into a string of characters:

char result[100];
int num = 24;
sprintf( result, "%d", num );

This code is similar, except that it converts a floating-point number into an array of characters:

char result[100];
float fnum = 3.14159;
sprintf( result, "%f", fnum );
Related topics
fprintf - printf
(Standard C String and Character) atof - atoi - atol

sscanf[edit]

Syntax
#include <cstdio>
int sscanf( const char *buffer, const char *format, ... );

The function sscanf() is just like scanf(), except that the input is read from buffer.

Related topics
fscanf - scanf

tmpfile[edit]

Syntax
#include <cstdio>
FILE *tmpfile( void );

The function tmpfile() opens a temporary file with a unique filename and returns a pointer to that file. If there is an error, null is returned.

Related topics
tmpnam

tmpnam[edit]

Syntax
#include <cstdio>
char *tmpnam( char *name );

The tmpnam() function creates a unique filename and stores it in name. tmpnam() can be called up to TMP_MAX times.

Related topics
tmpfile

ungetc[edit]

Syntax
#include <cstdio>
int ungetc( int ch, FILE *stream );

The function ungetc() puts the character ch back in stream.

Related topics
getc
(C++ I/O) putback

vprintf, vfprintf, and vsprintf[edit]

Syntax
#include <cstdarg>
#include <cstdio>
int vprintf( char *format, va_list arg_ptr );
int vfprintf( FILE *stream, const char *format, va_list arg_ptr );
int vsprintf( char *buffer, char *format, va_list arg_ptr );

These functions are very much like printf(), fprintf(), and sprintf(). The difference is that the argument list is a pointer to a list of arguments. va_list is defined in cstdarg, and is also used by (Other Standard C Functions) va_arg().

For example:

void error( char *fmt, ... ) {
  va_list args;
  va_start( args, fmt );
  fprintf( stderr, "Error: " );
  vfprintf( stderr, fmt, args );
  fprintf( stderr, "\n" );
  va_end( args );
  exit( 1 );
}