c library for input output operations.cstdio.(stdio.h)

83
cstdio (stdio.h) header C library to perform Input/Output operations Input and Output operations can also be performed in C++ using the C Standard Input and Output Library (cstdio, known as stdio.h in the C language). This library uses what are called streams to operate with physical devices such as keyboards, printers, terminals or with any other type of files supported by the system. Streams are an abstraction to interact with these in an uniform way; All streams have similar properties independently of the individual characteristics of the physical media they are associated with. Streams are handled in the cstdio library as pointers to FILE objects. A pointer to a FILE object uniquely identifies a stream, and is used as a parameter in the operations involving that stream. There also exist three standard streams: stdin, stdout, and stderr, which are automatically created and opened for all programs using the library. Stream properties Streams have some properties that define which functions can be used on them and how these will treat the data input or output through them. Most of these properties are defined at the moment the stream is associated with a file (opened) using the fopen function: Read/Write Access Specifies whether the stream has read or write access (or both) to the physical media they are associated with. Text / Binary Text streams are thought to represent a set of text lines, each one ending with a new-line character. Depending on the environment where the application is run some character translation may occur with text streams to adapt some special characters to the text file specifications of the environment. A binary stream, on the other hand, is a sequence of characters written or read from the physical media with no translation, having a one-to-one correspondence with the characters read or written to the stream. Buffer A buffer is a block of memory where data is accumulated before being physically read or written to the associated file or device. Streams can be either fully buffered, line buffered or unbuffered. On fully buffered streams, data is read/written when the buffer is filled, on line buffered streams this happens when a new-line character is encountered, and on unbuffered streams characters are intended to be read/written as soon as possible. Indicators Streams have certain internal indicators that specify their current state and which affect the behavior of some input and output operations performed on them: Error indicator This indicator is set when an error has occurred in an operation related to the stream This indicator can be checked with the ferror function, and can be reset by calling either to clearerr or to any repositioning function (rewind, fseek and fsetpos).

Upload: leonard-horobet-stoian

Post on 15-Aug-2015

119 views

Category:

Software


0 download

TRANSCRIPT

cstdio (stdio.h) header

C library to perform Input/Output operations

Input and Output operations can also be performed in C++ using the C Standard Input and Output Library (cstdio, known as stdio.h in the C language). This library uses what are called streams to operate with physical devices such as keyboards, printers, terminals or with any other type of files supported by the system. Streams are an abstraction to interact with these in an uniform way; All streams have similar properties independently of the individual characteristics of the physical media they are associated with.

Streams are handled in the cstdio library as pointers to FILE objects. A pointer to a FILE object uniquely identifies a stream, and is used as a parameter in the operations involving that stream.

There also exist three standard streams: stdin, stdout, and stderr, which are automatically created and opened for all programs using the library.

Stream properties Streams have some properties that define which functions can be used on them and how these will treat the data input or output through them. Most of these properties are defined at the moment the stream is associated with a file (opened) using the fopen function:

Read/Write Access Specifies whether the stream has read or write access (or both) to the physical media they are associated with.

Text / Binary Text streams are thought to represent a set of text lines, each one ending with a new-line character. Depending on the environment where the application is run some character translation may occur with text streams to adapt some special characters to the text file specifications of the environment. A binary stream, on the other hand, is a sequence of characters written or read from the physical media with no translation, having a one-to-one correspondence with the characters read or written to the stream.

Buffer A buffer is a block of memory where data is accumulated before being physically read or written to the associated file or device. Streams can be either fully buffered, line buffered or unbuffered. On fully buffered streams, data is read/written when the buffer is filled, on line buffered streams this happens when a new-line character is encountered, and on unbuffered streams characters are intended to be read/written as soon as possible.

Indicators Streams have certain internal indicators that specify their current state and which affect the behavior of some input and output operations performed on them:

Error indicator This indicator is set when an error has occurred in an operation related to the stream This indicator can be checked with the ferror function, and can be reset

by calling either to clearerr or to any repositioning function (rewind, fseek

and fsetpos).

End-Of-File indicator When set, indicates that the last reading or writing operation performed with the stream reached the End of File. It can be checked with the feof function, and

can be reset by calling either to clearerr or to any repositioning function

(rewind, fseek and fsetpos).

Position indicator It is an internal pointer of each stream which points to the next character to be read or written in the next I/O operation. Its value can be obtained by the ftell

and fgetpos functions, and can be changed using the repositioning functions

rewind, fseek and fsetpos.

Functions Operations on files:

remove Remove file (function)

rename Rename file (function)

tmpfile Open a temporary file (function)

tmpnam Generate temporary filename (function)

File access:

fclose Close file (function)

fflush Flush stream (function)

fopen Open file (function)

freopen Reopen stream with different file or mode (function)

setbuf Set stream buffer (function)

setvbuf Change stream buffering (function)

Formatted input/output:

fprintf Write formatted output to stream (function)

fscanf Read formatted data from stream (function)

printf Print formatted data to stdout (function)

scanf Read formatted data from stdin (function)

snprintf Write formatted output to sized buffer (function)

sprintf Write formatted data to string (function)

sscanf Read formatted data from string (function)

vfprintf Write formatted data from variable argument list to stream (function)

vfscanf Read formatted data from stream into variable argument list (function)

vprintf Print formatted data from variable argument list to stdout (function)

vscanf Read formatted data into variable argument list (function)

vsnprintf Write format. data from variable argument list to sized buffer (function)

vsprintf Write formatted data from variable argument list to string (function)

vsscanf Read formatted data from string into variable argument list (function)

Character input/output:

fgetc Get character from stream (function)

fgets Get string from stream (function)

fputc Write character to stream (function)

fputs Write string to stream (function)

getc Get character from stream (function)

getchar Get character from stdin (function)

gets Get string from stdin (function)

putc Write character to stream (function)

putchar Write character to stdout (function)

puts Write string to stdout (function)

ungetc Unget character from stream (function)

Direct input/output:

fread Read block of data from stream (function)

fwrite Write block of data to stream (function)

File positioning:

fgetpos Get current position in stream (function)

fseek Reposition stream position indicator (function)

fsetpos Set position indicator of stream (function)

ftell Get current position in stream (function)

rewind Set position indicator to the beginning (function)

Error-handling:

clearerr Clear error indicators (function)

feof Check End-of-File indicator (function)

ferror Check error indicator (function)

perror Print error message (function)

Macros

BUFSIZ Buffer size (constant)

EOF End-of-File (constant)

FILENAME_MAX Maximum length of file names (constant)

FOPEN_MAX Potential limit of simultaneous open streams (constant)

L_tmpnam Minimum length for temporary file name (constant)

NULL Null pointer (macro)

TMP_MAX Number of temporary files (constant)

Additionally: _IOFBF, _IOLBF, _IONBF (used with setvbuf)

and SEEK_CUR, SEEK_END and SEEK_SET (used with fseek).

Types

FILE Object contain information to control a stream (type)

fpos_t Object contain information to specify position within a file (type)

size_t Unsigned integral type (type)

stderr object <cstdio>

FILE * stderr; Standard error stream

The standard error stream is the default destination for error messages and other diagnostic warnings. Like stdout, it is usually also directed to the output device of the standard console (generally, the screen). stderr can be used as an argument for any function that expects an output stream as one of its parameters, like fputs or fprintf.

Although generally both stdout and stderr are associated with the same console output, applications may differentiate between what is sent to stdout and what to stderr for the case that one of them is redirected. For example, it is frequent to redirect the regular output of a console program (stdout) to a file while expecting the error messages to keep appearing in the console screen.

It is also possible to redirect stderr to some other destination from within a program using the freopen function.

stdin object <cstdio>

FILE * stdin; Standard input stream

The standard input stream is the default source of data for applications. It is usually directed to the input device of the standard console (generally, a keyboard).

stdin can be used as an argument for any function that expects an input stream as one of its parameters, like fgets or fscanf.

Although it is generally safe to assume that the source of data for stdin is going to be a keyboard, bear in mind that this may not be the case even in regular console systems, since stdin can be redirected at the operating system level. For example, many systems, among them DOS/Windows and most UNIX shells, support the following command syntax: myapplication < example.txt to use the content of the file example.txt as the primary source of data for myapplication instead of the console keyboard.

It is also possible to redirect stdin to some other source of data from within a program using the freopen function.

stdout object <cstdio>

FILE * stdout; Standard output stream

The standard output stream is the default destination of regular output for applications. It is usually directed to the output device of the standard console (generally, the screen).

stdout can be used as an argument for any function that expects an output stream as one of its parameters, like fputs or fprintf.

Although it is generally safe to assume that the default destination for stdout is going to be the screen, bear in mind that this may not be the case even in regular console systems, since stdout can be redirected at the operating system level. For example, many systems, among them DOS/Windows and most UNIX shells, support the following command syntax:

myapplication > example.txt to redirect the output of myapplication to the file example.txt instead of the screen.

It is also possible to redirect stdout to some other source of data from within a program using the freopen function.

clearerr function <cstdio>

void clearerr ( FILE * stream ); Clear error indicators

Resets both the error and the EOF indicators of the stream. When a stream function fails either because of an error or because the end-of-file has been reached, one of these internal indicators may be set. These indicators remain set until either this, rewind, fseek or fsetpos is called.

Parameters stream

Pointer to a FILE object that identifies the stream.

Return Value None

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

/* writing errors */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen("myfile.txt","r"); if (pFile==NULL) perror ("Error opening file"); else { fputc ('x',pFile); if (ferror (pFile)) { printf ("Error Writing to myfile.txt\n"); clearerr (pFile); } fgetc (pFile); if (!ferror (pFile)) printf ("No errors reading myfile.txt\n"); fclose (pFile); } return 0; }

Edit & Run

This program opens an existing file called myfile.txt for reading and causes an I/O error trying to write on it. That error is cleared using clearerr, so a second error checking returns false.

Output: Error Writing to myfile.txt No errors reading myfile.txt

See also feof Check End-of-File indicator (function)

ferror Check error indicator (function)

rewind Set position indicator to the beginning (function)

fclose function <cstdio>

int fclose ( FILE * stream ); Close file

Closes the file associated with the stream and disassociates it.

All internal buffers associated with the stream are flushed: the content of any unwritten buffer is written and the content of any unread buffer is discarded.

Even if the call fails, the stream passed as parameter will no longer be associated with the file.

Parameters stream

Pointer to a FILE object that specifies the stream to be closed.

Return Value If the stream is successfully closed, a zero value is returned. On failure EOF, is returned.

Example 1 2 3 4 5 6 7 8 9

/* fclose example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","wt"); fprintf (pFile, "fclose example"); fclose (pFile); return 0; }

Edit & Run

See also fopen Open file (function )

fflush Flush stream (function)

feof function <cstdio>

int feof ( FILE * stream ); Check End-of-File indicator

Checks whether the End-of-File indicator associated with stream is set, returning a value different from zero if it is.

This indicator is generally set by a previous operation on the stream that reached the End-of-File.

Further operations on the stream once the End-of-File has been reached will fail until either rewind, fseek or fsetpos is successfully called to set the position indicator to a new value.

Parameters stream

Pointer to a FILE object that identifies the stream.

Return Value A non-zero value is returned in the case that the End-of-File indicator associated with the stream is set. Otherwise, a zero value is returned.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16

/* feof example: byte counter */ #include <stdio.h> int main () { FILE * pFile; long n = 0; pFile = fopen ("myfile.txt","rb"); if (pFile==NULL) perror ("Error opening file"); else { while (!feof(pFile)) { fgetc (pFile); n++; } fclose (pFile); printf ("Total number of bytes: %d\n", n-1); } return 0; }

Edit & Run

This code opens the file called myfile.txt, and counts the number of characters that it contains by reading all of them one by one. Finaly the total amount of bytes is printed out.

See also clearerr Clear error indicators (function)

ferror Check error indicator (function)

ferror function <cstdio>

int ferror ( FILE * stream ); Check error indicator

Checks if the error indicator associated with stream is set, returning a value different from zero if it is.

This indicator is generaly set by a previous operation on the stream that failed.

Parameters stream

Pointer to a FILE object that identifies the stream.

Return Value If the error indicator associated with the stream was set, the function returns a nonzero value. Otherwise, it returns a zero value.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13

/* ferror example: writing error */ #include <stdio.h> int main () { FILE * pFile; pFile=fopen("myfile.txt","r"); if (pFile==NULL) perror ("Error opening file"); else { fputc ('x',pFile); if (ferror (pFile)) printf ("Error Writing to myfile.txt\n"); fclose (pFile); } return 0; }

Edit & Run

This program opens an existing file called myfile.txt in read-only mode but tries to write a character to it, generating an error that is detected by ferror. Output: Error Writing to myfile.txt

See also feof Check End-of-File indicator (function)

clearerr Clear error indicators (function)

perror Print error message (function)

fflush function <cstdio>

int fflush ( FILE * stream ); Flush stream

If the given stream was open for writing and the last i/o operation was an output operation, any unwritten data in the output buffer is written to the file. If it was open for reading and the last operation was an input operation, the behavior depends on the specific library implementation. In some implementations this causes the input buffer to be cleared, but this is not standard behavior. If the argument is a null pointer, all open files are flushed. The stream remains open after this call. When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.

Parameters stream

Pointer to a FILE object that specifies a buffered stream.

Return Value A zero value indicates success. If an error occurs, EOF is returned and the error indicator is set (see feof).

Exemplu In files open for update (i.e., open for both reading and writting), the stream shall be flushed after an output operation before performing an input operation. This can be done either by repositioning (fseek, fsetpos, rewind) or by calling explicitly fflush, like in this example:

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15

/* fflush example */ #include <stdio.h> char mybuffer[80]; int main() { FILE * pFile; pFile = fopen ("example.txt","r+"); if (pFile == NULL) perror ("Error opening file"); else { fputs ("test",pFile); fflush (pFile); // flushing or repositioning required fgets (mybuffer,80,pFile); puts (mybuffer); fclose (pFile); return 0; } }

Edit & Run

See also fclose Close file (function)

fopen Open file (function)

setbuf Set stream buffer (function)

setvbuf Change stream buffering (function)

fgetc function <cstdio>

int fgetc ( FILE * stream ); Get character from stream

Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character.

fgetc and getc are equivalent, except that the latter one may be implemented as a macro.

Parameters stream

Pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return Value The character read is returned as an int value. If the End-of-File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferror or feof to determine whether an error happened or the End-of-File was reached.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

/* fgetc example: money counter */ #include <stdio.h> int main () { FILE * pFile; int c; int n = 0; pFile=fopen ("myfile.txt","r"); if (pFile==NULL) perror ("Error opening file"); else { do { c = fgetc (pFile); if (c == '$') n++; } while (c != EOF); fclose (pFile); printf ("File contains %d dollar sign chars ($).\n",n); } return 0; }

Edit & Run

This program reads an existing file called myfile.txt character by character and uses the n variable to count how many dollar characters ($) does the file contain.

See also getc Get character from stream (function)

fputc Write character to stream (function)

fread Read block of data from stream (function)

fscanf Read formatted data from stream (function)

fgetpos function <cstdio>

int fgetpos ( FILE * stream, fpos_t * position ); Get current position in stream

Gets the information needed to uniquely identify the current value of the stream's position indicator and stores it in the location pointed by position. The parameter position should point to an already allocated object of the type fpos_t, which is only intended to be used as a paremeter in future calls to fsetpos. To retrieve the value of the internal file position indicator as an integer value, use ftell function instead.

Parameters stream

Pointer to a FILE object that identifies the stream.

position Pointer to a fpos_t object.

Return Value The function return a zero value on success, and a non-zero value in case of error.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

/* fgetpos example */ #include <stdio.h> int main () { FILE * pFile; int c; int n; fpos_t pos; pFile = fopen ("myfile.txt","r"); if (pFile==NULL) perror ("Error open file"); else { c = fgetc (pFile); printf ("1st character is %c\n",c); fgetpos (pFile,&pos); for (n=0;n<3;n++) { fsetpos (pFile,&pos); c = fgetc (pFile); printf ("2nd character is %c\n",c); } fclose (pFile); } return 0; }

Edit & Run Output: 1st character is A 2nd character is B 2nd character is B 2nd character is B The example opens myfile.txt, reads the first character once and then it reads 3 times the same second character.

See also fsetpos Set position indicator of stream (function)

ftell Get current position in stream (function)

fseek Reposition stream position indicator (function)

fgets function <cstdio>

char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string.

Parameters str

Pointer to an array of chars where the string read is stored. num

Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

stream Pointer to a FILE object that identifies the stream where characters are read from. To read from the standard input, stdin can be used for this parameter.

Return Value On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned. Use either ferror or feof to check whether an error happened or the End-of-File was reached.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12

/* fgets example */ #include <stdio.h> int main() { FILE * pFile; char mystring [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { if ( fgets (mystring , 100 , pFile) != NULL ) puts (mystring); fclose (pFile); } return 0; }

Edit & Run

This example reads the first line of myfile.txt or the first 100 characters, whichever comes first, and prints them on the screen.

See also fputs Write string to stream (function)

fgetc Get character from stream (function)

gets Get string from stdin (function)

fopen function <cstdio>

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

Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.

The operations that are allowed on the stream and how these are performed are defined by the mode parameter.

The returned stream is fully buffered by default if it is known to not refer to an interactive device (see setbuf).

The returned pointer can be disassociated from the file by calling fclose or freopen. All opened files are automatically closed on normal program termination.

The running environment supports at least FOPEN_MAX files open simultaneously.

Parameters filename

C string containing the name of the file to be opened. Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).

mode C string containing a file access mode. It can be:

"r" read: Open file for input operations. The file must exist.

"w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and file is treated as a new empty file.

"a" append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.

"r+" read/update: Open a file for update (both for input and output). The file must exist.

"w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.

"a+"

append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b"character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").

The new C standard (C2011, which is not part of C++) adds a new standard subspecifier ("x"), that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.

If additional characters follow the sequence, the behavior depends on the library implementation: some implementations may ignore additional characters so that for example an additional "t" (sometimes used to explicitly state a text file) is accepted.

On some library implementations, opening or creating a text file with update mode may treat the stream instead as a binary file.

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

For files open for update (those which include a "+" sign), on which both input and output operations are allowed, the stream shall be flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a reading operation that follows a writing operation. The stream shall be repositioned (fseek, fsetpos, rewind) before a writing operation that follows a reading operation (whenever that operation did not reach the End-of-File).

Return Value

If the file is successfully opened, the function returns a pointer to a FILE object that can be used to identify the stream on future operations. Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.

Exemplu 1 2 3 4 5 6 7 8 9

/* fopen example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } return 0; }

Edit & Run

See also fclose Close file (function)

freopen Reopen stream with different file or mode (function)

setbuf Set stream buffer (function)

setvbuf Change stream buffering (function)

tmpfile Open a temporary file (function)

tmpnam Generate temporary filename (function)

fprintf function <cstdio>

int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream

Writes to the specified stream a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.

Parameters stream

Pointer to a FILE object that identifies the stream. format

C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. The number of arguments following the format parameters should at least be as much as the number of format tags. The format tags follow this prototype:

%[flags][width][.precision][length]specifier Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument:

specifier Output Example c Character a d or i Signed decimal integer 392 u Unsigned decimal integer 7235 o Signed octal 610 x Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (capital letters) 7FA f Decimal floating point, lowercase 392.65 F Decimal floating point, uppercase 392.65 e Scientific notation (mantissa/exponent) using e character 3.9265e+2 E Scientific notation (mantissa/exponent) using E character 3.9265E+2 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 a Hexadecimal floating point, lowercase -0xc.90fep-2 A Hexadecimal floating point, uppercase -0XC.90FEP-2 c Character a s String of characters sample p Pointer address b8000000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to the stream. The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for posi-tive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed):

specifiers

length d i u o x X f F e E g G a A c s p n

(none) int unsigned int double int char* void* int*

hh signed char unsigned char signed char*

h short int unsigned short int short int*

l long int unsigned long int wint_t wchar_t* long int*

ll long long int unsigned long long int long long int*

j intmax_t uintmax_t intmax_t*

z size_t size_t size_t*

t ptrdiff_t ptrdiff_t ptrdiff_t*

L

long double

Note that the c specifier takes an int (or wint_t) as argument, but performs the proper conversion to a char value (or a wchar_t) before formatting it for output. Note: Yellow rows indicate specifiers and sub-specifiers introduced by C99. See <cinttypes> for the specifiers for extended types. additional arguments Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.

Return Value On success, the total number of characters written is returned. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned. On failure, a negative number is returned.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13

/* fprintf example */ #include <stdio.h> int main () { FILE * pFile; int n; char name [100]; pFile = fopen ("myfile.txt","w"); for (n=0 ; n<3 ; n++) { puts ("please, enter a name: "); gets (name); fprintf (pFile, "Name %d [%-10.10s]\n",n,name); } fclose (pFile); return 0; }

Edit & Run

This example prompts 3 times the user for a name and then writes them to myfile.txt each one in a line with a fixed length (a total of 19 characters + newline). Two format tags are used: %d : Signed decimal integer %-10.10s : left aligned (-), minimum of ten characters (10), maximum of ten characters (.10), String (s). Assuming that we have entered John, Jean-Francois and Yoko as the 3 names, myfile.txt would contain:

myfile.txt Name 1 [John ] Name 2 [Jean-Franc] Name 3 [Yoko ]

For more examples on formatting see printf.

See also printf Print formatted data to stdout (function)

fscanf Read formatted data from stream (function)

fwrite Write block of data to stream (function)

fputs Write string to stream (function)

fputc function <cstdio>

int fputc ( int character, FILE * stream ); Write character to stream

Writes a character to the stream and advances the position indicator.

The character is written at the position indicated by the internal position indicator of the stream, which is then automatically advanced by one.

Parameters character

The int promotion of the character to be written. The value is internally converted to an unsigned char when written.

stream Pointer to a FILE object that identifies the stream where the character is to be written.

Return Value On success, the character written is returned. If a writing error occurs, EOF is returned and the error indicator (ferror) is set.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13

/* fputc example: alphabet writer */ #include <stdio.h> int main () { FILE * pFile; char c; pFile = fopen ("alphabet.txt","w"); if (pFile!=NULL) { for (c = 'A' ; c <= 'Z' ; c++) { fputc ( (int) c , pFile ); } fclose (pFile); } return 0; }

Edit & Run

This program creates a file called alphabet.txt and writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to it.

See also putc Write character to stream (function)

fgetc Get character from stream (function)

fwrite Write block of data to stream (function)

fopen Open file (function)

fputs function <cstdio>

int fputs ( const char * str, FILE * stream ); Write string to stream

Writes the C string pointed by str to the stream.

The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Notice that fputs not only differs from puts in that the destination stream can be specified, but also fputs does not write additional characters, while puts appends a newline character at the end automatically.

Parameters str

C string with the content to be written to stream. stream

Pointer to a FILE object that identifies an output stream.

Return Value On success, a non-negative value is returned. On error, the function returns EOF and sets the error indicator (ferror).

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13

/* fputs example */ #include <stdio.h> int main () { FILE * pFile; char sentence [256]; printf ("Enter sentence to append: "); fgets (sentence,255,stdin); pFile = fopen ("mylog.txt","a"); fputs (sentence,pFile); fclose (pFile); return 0; }

Edit & Run

This program allows to append a line to a file called mylog.txt each time it is run.

See also puts Write string to stdout (function)

fgets Get string from stream (function)

fputc Write character to stream (function)

fprintf Write formatted output to stream (function)

fwrite Write block of data to stream (function)

fread function <cstdio>

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ); Read block of data from stream

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.

The postion indicator of the stream is advanced by the total amount of bytes read.

The total amount of bytes read if successful is (size * count).

Parameters ptr

Pointer to a block of memory with a size of at least (size*count) bytes, converted to a void*.

size Size, in bytes, of each element to be read. size_t is an unsigned integral type.

count Number of elements, each one with a size of size bytes. size_t is an unsigned integral type.

stream Pointer to a FILE object that specifies an input stream.

Return Value The total number of elements successfully read is returned. If this number differs from the count parameter, either a reading error occurred or the end-of-file was reached while reading. In both cases, the proper indicator is set, which can be checked with ferror and feof, respectively. If either size or count is zero, the function returns zero and both the stream state and the content pointed by ptr remain unchanged. size_t is an unsigned integral type.

Exemplu 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16

/* fread example: read a complete file */ #include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen ( "myfile.bin" , "rb" ); if (pFile==NULL) {fputs ("File error",stderr); exit (1);} // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile);

Edit & Run

17 18 19 20 21 22 23 24 25

// copy the file into the buffer: result = fread (buffer,1,lSize,pFile); if (result != lSize) {fputs ("Reading error",stderr); exit (3);} /* the whole file is now loaded in the memory buffer. */ // terminate fclose (pFile); free (buffer); return 0; }

This code loads myfile.bin into a dynamically allocated memory buffer, which can be used to manipulate the content of a file as an array.

See also fwrite Write block of data to stream (function)

fgetc Get character from stream (function)

fscanf Read formatted data from stream (function)

freopen function <cstdio>

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

Reopen stream with different file or mode

freopen first tries to close any file already associated with the stream given as third parameter and disassociates it. Then, whether that stream was successfuly closed or not, freopen opens the file whose name is passed in the first parameter, filename, and associates it with the specified stream just as fopen would do using the mode value specified as the second parameter. This function is specially useful for redirecting predefined streams like stdin, stdout and stderr to specific files (see the example below).

Parameters filename

C string containing the name of the file to be opened. This parameter must follow the file specifications of the running environment and can include a path if the system supports it. If this parameter is a null pointer, the function attemps to change the mode of the stream specified as third parater to the one specified in the modeparameter, as if the file name currently associated with that stream had been used.

mode C string containing the file access modes. It can be: "r" Open a file for reading. The file must exist.

"w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

"a" Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.

"r+" Open a file for update both reading and writing. The file must exist.

"w+" Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

"a+"

Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

An additional b is used to specify the file is to be reopened in binary mode. For more details on these modes, refer to fopen.

stream pointer to a FILE object that identifies the stream to be reopened.

Return Value If the file was successfully reopened, the function returns a pointer to an object identifying the stream. Otherwise, a null pointer is returned.

Example 1 2 3 4 5 6 7 8 9

10

/* freopen example: redirecting stdout */ #include <stdio.h> int main () { freopen ("myfile.txt","w",stdout); printf ("This sentence is redirected to a file."); fclose (stdout); return 0; }

This sample code redirects the output that would normally go to the standard output to a file called myfile.txt, that after this program is executed contains: This sentence is redirected to a file.

See also fopen Open file (function )

fclose Close file (function)

fscanf function <cstdio>

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

Read formatted data from stream

Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

Parameters stream

Pointer to a FILE object that identifies the stream to read data from. format

C string that contains one or more of the following items:

Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.

Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character offormat. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored in the locations pointed by the additional arguments. A format specifier follows this prototype: [=%[*][width][modifiers]type=] where:

* An optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument.

width Specifies the maximum number of characters to be read in the current reading operation

modifiers

Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)

type A character specifying the type of data to be read and how it is expected to be read. See next table.

fscanf type specifiers:

type Qualifying Input Type of argument

c

Single character: Reads the next character. If a width different from 1 is specified, the function reads widthcharacters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.

char *

d Decimal integer: Number optionally preceeded with a + or - sign.

int *

e,E,f,g,G

Floating point: Decimal number containing a decimal point, optionally preceeded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4

float *

o Octal integer. int *

s

String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

char *

u Unsigned decimal integer. unsigned int *

x,X Hexadecimal integer. int *

additional arguments The function expects a sequence of references as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order. For each format specifier in the format string that retrieves data, an additional argument should be specified. These arguments are expected to be references (pointers): if you want to store the result of a fscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like in: int n; fscanf (stream,"%d",&n);

Return Value On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned.

Example

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18

/* fscanf example */ #include <stdio.h> int main () { char str [80]; float f; FILE * pFile; pFile = fopen ("myfile.txt","w+"); fprintf (pFile, "%f %s", 3.1416, "PI"); rewind (pFile); fscanf (pFile, "%f", &f); fscanf (pFile, "%s", str); fclose (pFile); printf ("I have read: %f and %s \n",f,str); return 0; }

This sample code creates a file called myfile.txt and writes a float number and a string to it. Then, the stream is rewinded and both values are read withfscanf. It finally produces an output similar to: I have read: 3.141600 and PI

See also scanf Read formatted data from stdin (function )

fprintf Write formatted output to stream (function )

fread Read block of data from stream (function)

fgets Get string from stream (function ) int fseek ( FILE * stream, long int offset, int origin );

Reposition stream position indicator

Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin. The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped. When using fseek on text files with offset values other than zero or values retrieved with ftell, bear in mind that on some platforms some format transformations occur with text files which can lead to unexpected repositioning. On streams open for update (read+write), a call to fseek allows to switch between reading and writing.

Parameters stream

Pointer to a FILE object that identifies the stream. offset

Number of bytes to offset from origin. origin

Position from where offset is added. It is specified by one of the following constants defined in <cstdio>: SEEK_SET Beginning of file SEEK_CUR Current position of the file pointer SEEK_END End of file

Return Value If successful, the function returns a zero value. Otherwise, it returns nonzero value.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13

/* fseek example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ( "example.txt" , "w" ); fputs ( "This is an apple." , pFile ); fseek ( pFile , 9 , SEEK_SET ); fputs ( " sam" , pFile ); fclose ( pFile ); return 0; }

After this code is successfully executed, the file example.txt contains: This is a sample.

See also ftell Get current position in stream (function)

fsetpos Set position indicator of stream (function)

rewind Set position indicator to the beginning (function)

fsetpos function <cstdio>

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

Set position indicator of stream

Changes the internal file position indicator associated with stream to a new position. The position parameter is a pointer to an fpos_t object whose value shall have been previously obtained with a call to fgetpos. The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped. On streams open for update (read+write), a call to fsetpos allows to switch between reading and writing.

Parameters stream

Pointer to a FILE object that identifies the stream. position

Pointer to a fpos_t object containing a position previously obtained with fgetpos.

Return Value If successful, the function returns a zero value. Otherwise, it returns a nonzero value and sets the global variable errno to a positive value, which can be interpreted with perror.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16

/* fsetpos example */ #include <stdio.h> int main () { FILE * pFile; fpos_t position; pFile = fopen ("myfile.txt","w"); fgetpos (pFile, &position); fputs ("That is a sample",pFile); fsetpos (pFile, &position); fputs ("This",pFile); fclose (pFile); return 0; }

After this code is successfully executed, a file called myfile.txt will contain: This is a sample

See also fgetpos Get current position in stream (function)

fseek Reposition stream position indicator (function)

rewind Set position indicator to the beginning (function)

ftell function <cstdio>

long int ftell ( FILE * stream );

Get current position in stream

Returns the current value of the position indicator of the stream. For binary streams, the value returned corresponds to the number of bytes from the beginning of the file. For text streams, the value is not guaranteed to be the exact number of bytes from the beginning of the file, but the value returned can still be used to restore the position indicator to this position using fseek.

Parameters stream

Pointer to a FILE object that identifies the stream.

Return Value On success, the current value of the position indicator is returned. If an error occurs, -1L is returned, and the global variable errno is set to a positive value. This value can be interpreted by perror.

Example 1 2 3 4 5

/* ftell example : getting size of a file */ #include <stdio.h> int main () {

6 7 8 9

10 11 12 13 14 15 16 17 18 19

FILE * pFile; long size; pFile = fopen ("myfile.txt","rb"); if (pFile==NULL) perror ("Error opening file"); else { fseek (pFile, 0, SEEK_END); size=ftell (pFile); fclose (pFile); printf ("Size of myfile.txt: %ld bytes.\n",size); } return 0; }

This program prints out the size of myfile.txt in bytes.

See also fseek Reposition stream position indicator (function)

fgetpos Get current position in stream (function)

rewind Set position indicator to the beginning (function)

fwrite function <cstdio>

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

Write block of data to stream

Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream. The postion indicator of the stream is advanced by the total number of bytes written. The total amount of bytes written is (size * count).

Parameters ptr

Pointer to the array of elements to be written. size

Size in bytes of each element to be written. count

Number of elements, each one with a size of size bytes. stream

Pointer to a FILE object that specifies an output stream.

Return Value The total number of elements successfully written is returned as a size_t object, which is an integral data type. If this number differs from the count parameter, it indicates an error.

Example 1 2 3 4 5 6 7 8 9

10 11 12

/* fwrite example : write buffer */ #include <stdio.h> int main () { FILE * pFile; char buffer[] = { 'x' , 'y' , 'z' }; pFile = fopen ( "myfile.bin" , "wb" ); fwrite (buffer , 1 , sizeof(buffer) , pFile ); fclose (pFile); return 0; }

A file called myfile.bin is created and the content of the buffer is stored into it. For simplicity, the buffer contains char elements but it can contain any other type. sizeof(buffer) is the length of the array in bytes (in this case it is three, because the array has three elements of one byte each).

See also fread Read block of data from stream (function)

fprintf Write formatted output to stream (function )

putc Write character to stream (function)

fputc Write character to stream (function)

getc function <cstdio>

int getc ( FILE * stream );

Get character from stream

Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character. getc is equivalent to fgetc and also expects a stream as parameter, but getc may be implemented as a macro, so the argument passed to it should not be an expression with potential side effects. See getchar for a similar function without stream parameter.

Parameters stream

pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return Value The character read is returned as an int value. If the End-of-File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferroror feof to determine whether an error happened or the End-Of-File was reached.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20

/* getc example: money counter */ #include <stdio.h> int main () { FILE * pFile; int c; int n = 0; pFile=fopen ("myfile.txt","r"); if (pFile==NULL) perror ("Error opening file"); else { do { c = getc (pFile); if (c == '$') n++; } while (c != EOF); fclose (pFile); printf ("File contains %d$.\n",n); } return 0; }

This program reads an existing file called myfile.txt character by character and uses the n variable to count how many dollar characters ($) does the file

contain.

See also fgetc Get character from stream (function)

fputc Write character to stream (function)

fread Read block of data from stream (function)

fwrite Write block of data to stream (function)

getchar function <cstdio>

int getchar ( void );

Get character from stdin

Returns the next character from the standard input (stdin). It is equivalent to getc with stdin as its argument.

Parameters (none)

Return Value The character read is returned as an int value. If the End Of File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferroror feof to determine whether an error happened or the End-Of-File was reached.

Example 1 2 3 4 5 6 7 8 9

10

/* getchar example : typewriter */ #include <stdio.h> int main () { char c; puts ("Enter text. Include a dot ('.') in a sentence to exit:"); do { c=getchar(); putchar (c);

11 12 13

} while (c != '.'); return 0; }

A simple typewriter. Every sentence is echoed once ENTER has been pressed until a dot (.) is included in the text.

See also getc Get character from stream (function)

putchar Write character to stdout (function)

scanf Read formatted data from stdin (function )

gets function <cstdio>

char * gets ( char * str );

Get string from stdin

Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-File is reached. The ending newline character ('\n') is not included in the string. A null character ('\0') is automatically appended after the last character copied to str to signal the end of the C string. Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with gets while with fgetsit is. And second, gets does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by strto avoid buffer overflows.

Parameters str

Pointer to an array of chars where the C string is stored.

Return Value On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned.

Use either ferror or feof to check whether an error happened or the End-of-File was reached.

Example 1 2 3 4 5 6 7 8 9

10 11

/* gets example */ #include <stdio.h> int main() { char string [256]; printf ("Insert your full address: "); gets (string); printf ("Your address is: %s\n",string); return 0; }

See also fgets Get string from stream (function )

getchar Get character from stdin (function)

scanf Read formatted data from stdin (function )

perror function <cstdio>

void perror ( const char * str );

Print error message

Interprets the value of the global variable errno into a string and prints that string to stderr (standard error output stream, usually the screen), optionaly preceding it with the custom message specified in str. errno is an integral variable whose value describes the last error produced by a call to a library function. The error strings produced by perror depend on the developing platform and compiler. If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n'). perror should be called right after the error was produced, otherwise it can be overwritten in calls to other functions.

Parameters.

str C string containing a custom message to be printed before the error message itself. If it is a null pointer, no preceding custom message is printed, but the error message is printed anyway. By convention, the name of the application itself is generally used as parameter.

Return Value none

Example 1 2 3 4 5 6 7 8 9

10 11 12 13

/* perror example */ #include <stdio.h> int main () { FILE * pFile; pFile=fopen ("unexist.ent","rb"); if (pFile==NULL) perror ("The following error occurred"); else fclose (pFile); return 0; }

If the file unexist.ent does not exist, something similar to this Output is expected to be the program output: The following error occurred: No such file or directory

See also clearerr Clear error indicators (function)

ferror Check error indicator (function)

printf function <cstdio>

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

Print formatted data to stdout

Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects

at least as many additional arguments as specified in format.

Parameters format

String that contains the text to be written to stdout. It can optionally contain embedded format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of arguments following the format parameters should at least be as much as the number of format tags. The format tags follow this prototype: %[flags][width][.precision][length]specifier Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument: specifier Output Example c Character a

d or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character

3.9265e+2

E Scientific notation (mantissa/exponent) using E character

3.9265E+2

f Decimal floating point 392.65 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o Unsigned octal 610 s String of characters sample u Unsigned decimal integer 7235 x Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (capital letters) 7FA p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to stdout.

%

The tag can also contain flags, width, .precision and length sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are

preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number)

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide

character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

additional arguments

Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each%-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.

Return Value On success, the total number of characters written is returned. On failure, a negative number is returned.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15

/* printf example */ #include <stdio.h> int main() { printf ("Characters: %c %c \n", 'a', 65); printf ("Decimals: %d %ld\n", 1977, 650000L); printf ("Preceding with blanks: %10d \n", 1977); printf ("Preceding with zeros: %010d \n", 1977); printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); printf ("Width trick: %*d \n", 5, 10); printf ("%s \n", "A string"); return 0; }

And here is the output: Characters: a A Decimals: 1977 650000 Preceding with blanks: 1977 Preceding with zeros: 0000001977 Some different radixes: 100 64 144 0x64 0144 floats: 3.14 +3e+000 3.141600E+000 Width trick: 10 A string

See also puts Write string to stdout (function)

scanf Read formatted data from stdin (function )

fprintf Write formatted output to stream (function )

fwrite Write block of data to stream (function)

putc function <cstdio>

int putc ( int character, FILE * stream );

Write character to stream

Writes a character to the stream and advances the position indicator. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character. putc is equivalent to fputc and also expects a stream as parameter, but putc may be implemented as a macro, so the argument passed should not be an expression with potential side effects. See putchar for a similar function without stream parameter.

Parameters character

Character to be written. The character is passed as its int promotion. stream

Pointer to a FILE object that identifies the stream where the character is to be written.

Return Value If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.

Example 1 2 3 4 5 6 7

/* putc example: alphabet writer */ #include <stdio.h> int main () { FILE * pFile; char c;

8 9

10 11 12 13 14 15

pFile=fopen("alphabet.txt","wt"); for (c = 'A' ; c <= 'Z' ; c++) { putc (c , pFile); } fclose (pFile); return 0; }

This example program creates a file called alphabet.txt and writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to it.

See also putchar Write character to stdout (function)

fputc Write character to stream (function)

getc Get character from stream (function)

fwrite Write block of data to stream (function)

fprintf Write formatted output to stream (function )

putchar function <cstdio>

int putchar ( int character );

Write character to stdout

Writes character to the current position in the standard output (stdout) and advances the internal file position indicator to the next position. It is equivalent to putc(character,stdout).

Parameters character

Character to be written. The character is passed as its int promotion.

Return Value If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.

Example 1 2 3 4 5 6 7 8 9

10 11

/* putchar example: printing alphabet */ #include <stdio.h> int main () { char c; for (c = 'A' ; c <= 'Z' ; c++) { putchar (c); } return 0; }

This program writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to the standard output.

See also putc Write character to stream (function)

fputc Write character to stream (function)

getchar Get character from stdin (function)

puts function <cstdio>

int puts ( const char * str );

Write string to stdout

Writes the C string pointed by str to stdout and appends a newline character ('\n'). The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This final null-character is not copied tostdout. Using fputs(str,stdout) instead, performs the same operation as puts(str) but without appending the newline character at the end.

Parameters str

C string to be written.

Return Value On success, a non-negative value is returned. On error, the function returns EOF.

Example 1 2 3 4 5 6 7 8

/* puts example : hello world! */ #include <stdio.h> int main () { char string [] = "Hello world!"; puts (string); }

See also fputs Write string to stream (function)

printf Print formatted data to stdout (function )

putchar Write character to stdout (function)

gets Get string from stdin (function )

remove function <cstdio>

int remove ( const char * filename );

Remove file

Deletes the file whose name is specified in filename. This is an operation performed directly on a file; No streams are involved in the operation.

Parameters filename

C string containing the name of the file to be deleted. This parameter must follow the file name specifications of the running environment and can include a path if the system supports it.

Return value If the file is successfully deleted, a zero value is returned. On failure, a nonzero value is reurned and the errno variable is set to the corresponding error code. Error codes are numerical values representing the type of failure occurred. A string interpreting this value can be printed to the standard error stream by a call to perror.

Example 1 2 3 4 5 6 7 8 9

10 11

/* remove example: remove myfile.txt */ #include <stdio.h> int main () { if( remove( "myfile.txt" ) != 0 ) perror( "Error deleting file" ); else puts( "File successfully deleted" ); return 0; }

If the file myfile.txt existed before the execution and we had write access to it, then the file will be deleted and this message will be written to stdout: File successfully deleted Otherwise, a message similar to this will be written to stderr: Error deleting file: No such file or directory

See also rename Rename file (function )

rename function <cstdio>

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

Rename file

Changes the name of the file or directory specified by oldname to newname. If oldname and newname specify different paths and this is supported by the system, the file is moved to the new location. This is an operation performed directly on a file; No streams are involved in the operation.

Parameters oldname

C string containing the name of the file to be renamed and/or moved. This file must exist and the correct writing permissions should be available.

newname C string containing the new name for the file. This shall not be the name of an existing file; if it is, the behavior to be expected depends on the running environment, which may either be failure or overriding.

Return value If the file is successfully renamed, a zero value is returned. On failure, a nonzero value is returned and the errno variable is set to the corresponding error code. Error codes are numerical values representing the type of failure occurred. A string interpreting this value can be printed to the standard error stream by a call to perror.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15

/* rename example */ #include <stdio.h> int main () { int result; char oldname[] ="oldname.txt"; char newname[] ="newname.txt"; result= rename( oldname , newname ); if ( result == 0 ) puts ( "File successfully renamed" ); else perror( "Error renaming file" ); return 0; }

If the file oldname.txt could be successfully renamed to newname.txt the following message would be written to stdout: File successfully renamed Otherwise, a message similar to this will be written to stderr: Error renaming file: Permission denied

See also remove Remove file (function )

rewind function <cstdio>

void rewind ( FILE * stream );

Set position indicator to the beginning

Sets the position indicator associated with stream to the beginning of the file. A call to rewind is equivalent to: fseek ( stream , 0L , SEEK_SET ); except that, unlike fseek, rewind clears the error indicator. On streams open for update (read+write), a call to rewind allows to switch between reading and writing.

Parameters stream

Pointer to a FILE object that identifies the stream.

Return Value none

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

/* rewind example */ #include <stdio.h> int main () { int n; FILE * pFile; char buffer [27]; pFile = fopen ("myfile.txt","w+"); for ( n='A' ; n<='Z' ; n++) fputc ( n, pFile); rewind (pFile); fread (buffer,1,26,pFile); fclose (pFile); buffer[26]='\0'; puts (buffer); return 0; }

A file called myfile.txt is created for reading and writing and filled with the alphabet. The file is then rewinded, read and its content is stored in a buffer, that then is written to the standard output: ABCDEFGHIJKLMNOPQRSTUVWXYZ

See also fseek Reposition stream position indicator (function)

fsetpos Set position indicator of stream (function)

fflush Flush stream (function)

scanf function <cstdio>

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

Read formatted data from stdin

Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

Parameters format

C string that contains one or more of the following items:

Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.

Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from stdin, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next

character offormat. If the character does not match, the function fails, returning and leaving subsequent characters of stdin unread.

Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from stdin and stored in the locations pointed by the additional arguments. A format specifier follows this prototype: %[*][width][modifiers]type where:

* An optional starting asterisk indicates that the data is to be retrieved from stdin but ignored, i.e. it is not stored in the corresponding argument.

width Specifies the maximum number of characters to be read in the current reading operation

modifiers

Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)

type A character specifying the type of data to be read and how it is expected to be read. See next table.

scanf type specifiers:

type Qualifying Input Type of argument

c

Single character: Reads the next character. If a width different from 1 is specified, the function reads widthcharacters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.

char *

d Decimal integer: Number optionally preceded with a + or - sign.

int *

e,E,f,g,G

Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4

float *

o Octal integer. int *

s

String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

char *

u Unsigned decimal integer. unsigned int *

x,X Hexadecimal integer. int *

additional arguments The function expects a sequence of references as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order. For each format specifier in the format string that retrieves data, an additional argument should be specified. These arguments are expected to be references (pointers): if you want to store the result of a fscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like in: int n; scanf ("%d",&n);

Return Value On success, the function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

/* scanf example */ #include <stdio.h> int main () { char str [80]; int i; printf ("Enter your family name: "); scanf ("%s",str); printf ("Enter your age: "); scanf ("%d",&i); printf ("Mr. %s , %d years old.\n",str,i); printf ("Enter a hexadecimal number: "); scanf ("%x",&i); printf ("You have entered %#x (%d).\n",i,i); return 0; }

This example demonstrates some of the types that can be read with scanf: Enter your family name: Soulie Enter your age: 29 Mr. Soulie , 29 years old. Enter a hexadecimal number: ff You have entered 0xff (255).

See also fscanf Read formatted data from stream (function )

printf Print formatted data to stdout (function )

gets Get string from stdin (function )

fopen Open file (function )

setbuf function

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

Set stream buffer

Sets the buffer to be used for I/O operations with the specified stream, which becomes a fully buffered stream, or alternatively, if the argument for buffer isNULL, it disables buffering for the stream, which becomes an unbuffered stream. This function should be called once the file associated with the stream has already been opened but before any input or output operation has taken place. The buffer parameter must point to an array at least BUFSIZ bytes long (BUFSIZ is a constant defined in <cstdio>). With fully buffered streams, writing operations are not intended to be written directly to the device associated with them; the data is accumulated in the buffer and written to the device as a block when it is filled. This writing of the whole block can be forced by flushing the stream, which can be done by callingfflush or by closing the file (fclose). All buffers are also flushed when the program terminates. With unbuffered streams, data is written to the physical device as soon as possible after each writing operation. All files are opened with a default allocated buffer. This function can be used to define a user-allocated buffer or to disable buffering for a specific stream. System standard streams like stdout and stderr are unbuffered by default unless they are redirected. To change to a line buffered stream, use setvbuf instead.

Parameters stream

Pointer to a FILE object that identifies an open stream. buffer

User allocated buffer. Must have a length of at least BUFSIZ bytes, which is a macro constant defined in <cstdio> specifically designed to be used as the length of this array. Alternatively, a NULL pointer can be specified to disable buffering.

Return Value none

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20 21 22 23

/* setbuf example */ #include <stdio.h> int main () { char buffer[BUFSIZ]; FILE *pFile1, *pFile2; pFile1=fopen ("myfile.txt","w"); pFile2=fopen ("myfile2.txt","a"); setbuf ( pFile1 , buffer ); fputs ("This is sent to a buffered stream",pFile1); fflush (pFile1); setbuf ( pFile2 , NULL ); fputs ("This is sent to an unbuffered stream",pFile2); fclose (pFile1); fclose (pFile2); return 0; }

Two files are opened with writing access. The stream associated with the file myfile.txt is set to a user allocated buffer; a writing operation to it is performed; the data is logically part of the stream, but it has not been writen to the device until the fflush function is called. The second buffer in the example, associated with the file myfile2.txt, is set to unbuffered, so the subsequent output operation is written to the device as soon as possible. The final result, however, is the same with both buffered and unbuffered streams once the files have been closed.

See also fopen Open file (function )

fflush Flush stream (function)

setvbuf Change stream buffering (function )

setvbuf function <cstdio>

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

Change stream buffering

Changes the buffer to be used for I/O operations with the specified stream. The function allows to specify the mode and size for the buffer. This function should be called once the file associated with the stream has already been opened but before any input or output operation has taken place. The size of the buffer is specified by the size parameter in bytes. If no buffer is specified (i.e. the buffer argument is NULL), the system dynamically allocates the amount of memory requested by the function (size bytes) and uses it as the buffer for the stream. The mode parameter is used to specify if the buffer has to be fully buffered, line buffered or if the stream has to be unbuffered (see below). With full buffered streams, writing operations do not write directly to the physical device associated with them; instead, the data is accumulated in the buffer and written to the device as a block when the bufer is filled. This writing of the whole block can be forced by flushing the stream, which can be done by callingfflush or by closing the file (fclose). All buffers are also flushed when the program terminates. With line buffered streams, the buffer is writen to the physical device each time a new-line character is written. With unbuffered streams, data is written to the device as soon as possible after each writing operation. All files are opened with a default allocated buffer. This function can be used to either redefine the buffer size, define a user-allocated buffer or to disable buffering for the file. System standard streams like stdout and stderr are unbuffered by default if they are not redirected.

Parameters stream

Pointer to a FILE object that identifies an open stream. buffer

User allocated buffer. Must be at least size bytes long. If set to NULL, the function automatically allocates a buffer of the specified size.

mode Specifies a mode for file buffering:

_IOFBF Full buffering: On output, data is written once the buffer is full. On Input the buffer is filled when an input operation is requested and the buffer is empty.

_IOLBF

Line buffering: On output, data is written when a newline character is inserted into the stream or when the buffer is full, whatever happens first. On Input, the buffer is filled up to the next newline character when an input operation is requested and the buffer is empty.

_IONBF No buffering: No buffer is used. Each I/O operation is written as soon as possible. In this case, the buffer and size parameters are ignored.

size Buffer size in bytes. If the buffer argument is NULL, this determines the minimum size automatically allocated by the function for the buffer, otherwise it must be a value equal or lower to the size in bytes of the array specified as buffer.

Return Value If the buffer is correctly assigned to the file, a zero value is returned. Otherwise, a non-zero value is returned; This may be due to invalid mode or size parameters or to an error while allocating memory if NULL was specified asbuffer).

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

/* setvbuf example */ #include <stdio.h> int main () { FILE *pFile; pFile=fopen ("myfile.txt","w"); setvbuf ( pFile , NULL , _IOFBF , 1024 ); // File operations here fclose (pFile); return 0; }

In this example a file myfile.txt is created and a full buffer of 1024 bytes is assigned to its stream, so the data output to this stream should only be written to the file each time the 1024-byte buffer is full.

See also setbuf Set stream buffer (function )

fopen Open file (function )

fflush Flush stream (function)

sprintf function <cstdio>

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

Write formatted data to string

Writes into the array pointed by str a C string consisting on a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format. This function behaves exactly as printf does, but writing its results to a string instead of stdout. The size of the array passed as str should be enough to contain the entire formatted string.

Parameters str

Pointer to an array of char elements where the resulting C string is stored. format

C string that contains the text to be written to the buffer. It can optionally contain embedded format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested. The number of arguments following the format parameters should at least be as much as the number of format tags. The format tags follow this prototype: %[flags][width][.precision][length]specifier Where specifier is the most significant one and defines the type and the interpretation of the value of the corresponding argument: specifier Output Example c Character a

d or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character

3.9265e+2

E Scientific notation (mantissa/exponent) using E character

3.9265E+2

f Decimal floating point 392.65 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o Signed octal 610 s String of characters sample u Unsigned decimal integer 7235 x Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (capital letters) 7FA p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to the string.

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number)

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an

additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

additional arguments

Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each%-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.

Return Value On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string. On failure, a negative number is returned.

Example 1 2 3 4 5 6 7 8 9

10 11

/* sprintf example */ #include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a %d char long string\n",buffer,n); return 0; }

Output: [5 plus 3 is 8] is a 13 char long string

See also printf Print formatted data to stdout (function )

sscanf Read formatted data from string (function )

sscanf function <cstdio>

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

Read formatted data from string

Reads data from str and stores them according to the parameter format into the locations given by the additional arguments. Locations pointed by each additional argument are filled with their corresponding type of value specified in the format string.

Parameters str

C string that the function processes as its source to retrieve the data. format

C string that contains one or more of the following items:

Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.

Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from str, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format andstr. If the character does not match, the function fails and returns.

Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the str string and stored in the locations pointed by the additional arguments. A format specifier follows this prototype: [=%[*][width][modifiers]type=] where:

* An optional starting asterisk indicates that the data is to be retrieved from the str string but ignored, i.e. it is not stored in the corresponding argument.

width Specifies the maximum number of characters to be read in the current reading operation

modifiers

Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)

type A character specifying the type of data to be read and how it is expected to be read. See next table.

sscanf type specifiers:

type Qualifying Input Type of argument

c

Single character: Reads the next character. If a width different from 1 is specified, the function reads widthcharacters and stores them in the successive locations of the array passed as argument. No null character is

char *

appended at the end.

d Decimal integer: Number optionally preceeded with a + or - sign.

int *

e,E,f,g,G

Floating point: Decimal number containing a decimal point, optionally preceeded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4

float *

o Octal integer. int *

s

String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

char *

u Unsigned decimal integer. unsigned int *

x,X Hexadecimal integer. int *

additional arguments The function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order. For each format specifier in the format string that retrieves data, an additional argument should be specified. These arguments are expected to be references (pointers): if you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like in: int n; sscanf (str,"%d",&n);

Return Value On success, the function returns the number of variables filled. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

Example 1 2 3 4 5 6 7

/* sscanf example */ #include <stdio.h> int main () { char sentence []="Rudolph is 12 years old"; char str [20];

8 9

10 11 12 13 14

int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s -> %d\n",str,i); return 0; }

Output: Rudolph -> 12

See also scanf Read formatted data from stdin (function )

sprintf Write formatted data to string (function )

tmpfile function <cstdio>

FILE * tmpfile ( void );

Open a temporary file

Creates a temporary binary file, open for update (wb+ mode -- see fopen for details). The filename is guaranteed to be different from any other existing file. The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally.

Parameters none

Return Value If successful, the function returns a stream pointer to the temporary file created. If the file cannot be created, NULL is returned.

Example 1 2 3

/* tmpfile example */ #include <stdio.h>

4 5 6 7 8 9

10 11 12 13

int main () { FILE * pFile; pFile = tmpfile (); // temporary file created. code here. fclose (pFile); return 0; }

This code creates a temporary file and then deletes it closing the stream.

See also fopen Open file (function )

tmpnam Generate temporary filename (function)

tmpnam function <cstdio>

char * tmpnam ( char * str );

Generate temporary filename

A string containing a filename different from any existing file is generated. This string can be used to create a temporary file without overwriting any other existing file. If the str argument is a null pointer, the resulting string is stored in an internal static array that can be accessed by the return value. The content of this string is stored until a subsequent call to this same function erases it. If the str argument is not a null pointer, it must point to an array of at least L_tmpnam bytes that will be filled with the proposed tempname. L_tmpnam is a macro constant defined in <cstdio>. The file name returned by this function can be used to create a regular file using fopen to be used as a temp file. The file created this way, unlike those created with tmpfile is not automatically deleted when closed; You should call remove to delete this file once closed.

Parameters str

Pointer to an array of chars where the proposed tempname will be stored as a C string. The size of this array should be at least L_tmpnam characters. Alternativelly, a null pointer can be specified, in which case the string will

be stored in an internal static array that can be accessed with the return value.

Return Value A pointer to the C string containing the proposed name for a temporary file. If str was a null pointer, this points to an internal buffer that will be overwritten the next time this function is called. If str was not a null pointer, str is returned. If the function fails to create a suitable filename, it returns a null pointer.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16

/* tmpnam example */ #include <stdio.h> int main () { char buffer [L_tmpnam]; char * pointer; tmpnam (buffer); printf ("Tempname #1: %s\n",buffer); pointer = tmpnam (NULL); printf ("Tempname #2: %s\n",pointer); return 0; }

This program will generate two different names for temporary files. Each one has been created by one of the two methods in which tmpnam can be used.

See also fopen Open file (function )

tmpfile Open a temporary file (function)

ungetc function <cstdio>

int ungetc ( int character, FILE * stream );

Unget character from stream

A character is virtually put back into an input stream at the same position the last character was read and the internal file position indicator is decreased back to that previous position so that this character is returned by the next call to a reading operation on that stream. This character may or may not be the same character as the one last read from the stream in a previous operation. In both cases the value retrieved by the next reading operation on the stream is the one ungot by this function independently of the original character. Notice though, that this only affects the next reading operation on that character, not the content of the physical file associated with the stream, which is not modified by any calls to this function. More than one character can be ungot making them available for reading operations in the reverse order they were put back into the stream. If the End-Of-File internal indicator was set, it is cleared after a call to this function. A call to fseek, fsetpos or rewind on a stream will discard any characters previously put back into it with this function. If the argument passed for the character parameter is EOF, the operation fails and the input stream remains unchanged.

Parameters character

Character to be put back. The character is passed as its int promotion. stream

Pointer to a FILE object that identifies an input stream.

Return Value If successful, the character that was pushed back is returned. On falure, EOF is returned and the stream remains unchanged.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14

/* ungetc example */ #include <stdio.h> int main () { FILE * pFile; int c; char buffer [256]; pFile = fopen ("myfile.txt","rt"); if (pFile==NULL) perror ("Error opening file"); else { while (!feof (pFile)) { c=getc (pFile);

15 16 17 18 19 20 21 22 23 24 25

if (c == '#') ungetc ('@',pFile); else ungetc (c,pFile); fgets (buffer,255,pFile); fputs (buffer,stdout); } } return 0; }

This example opens an existing file called myfile.txt for reading and prints its lines, but first gets the first character of every line and puts it back into the stream except if the line begins with #, in which case it is replaced by @.

See also getc Get character from stream (function)

fgetc Get character from stream (function)

putc Write character to stream (function)

vfprintf function <cstdio>

int vfprintf ( FILE * stream, const char * format, va_list arg );

Write formatted variable argument list to stream

Writes to the specified stream the contents of the format string, expanding the format tags with the values of the argument list arg. This function behaves exactly as fprintf except that the variable argument list is passed as a va_list instead of a succession of arguments, which becomes specially useful when the argument list to be passed comes itself from a variable argument list in the calling function. vfprintf does not automatically call the va_end macro.

Parameters stream

Pointer to a FILE object that identifies the stream. format

C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are substituted by

the values specified in subsequent argument(s) and formatted as requested. The number of arguments following the format parameters should at least be as much as the number of format tags. The format tags follow this prototype: %[flags][width][.precision][length]specifier Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument: specifier Output Example c Character a

d or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character

3.9265e+2

E Scientific notation (mantissa/exponent) using E character

3.9265E+2

f Decimal floating point 392.65 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o Signed octal 610 s String of characters sample u Unsigned decimal integer 7235 x Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (capital letters) 7FA p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to the stream.

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written.

Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number)

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after de decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

arg

An object representing the variable arguments list. It shall have already been initialized by the va_start macro defined in cstdarg.

Return Value On success, the total number of characters written is returned. On failure, a negative number is returned.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

/* vfprintf example */ #include <stdio.h> #include <stdarg.h> void WriteFormatted (FILE * stream, char * format, ...) { va_list args; va_start (args, format); vfprintf (stream, format, args); va_end (args); } int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); WriteFormatted (pFile,"Call with %d variable argument.\n",1); WriteFormatted (pFile,"Call with %d variable %s.\n",2,"arguments"); fclose (pFile); return 0; }

The example demonstrates how the WriteFormatted can be called with a different number of arguments, which are on their turn passed to the vfprintffunction. myfile.txt would contain:

myfile.txt Call with 1 variable argument. Call with 2 variable arguments.

See also vprintf Print formatted variable argument list to stdout (function )

vsprintf Print formatted variable argument list to string (function )

fprintf Write formatted output to stream (function )

printf Print formatted data to stdout (function )

vprintf function <cstdio>

int vprintf ( const char * format, va_list arg );

Print formatted variable argument list to stdout

Writes to stdout the contents of the format string, expanding the format tags with the value of the argument list arg. This function behaves exactly as printf except that the variable argument list is passed as a va_list instead of a succession of arguments, which becomes specially useful when the argument list to be passed comes itself from a variable argument list in the calling function. vprintf does not automatically call the va_end macro.

Parameters format

String that contains the text to be written to stdout. It can optionally contain embedded format tags that are substituted by the values specified in the arg variable argument list and formatted as requested. The format tags follow this prototype: %[flags][width][.precision][length]specifier Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument: specifier Output Example c Character a

d or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character

3.9265e+2

E Scientific notation (mantissa/exponent) using E character

3.9265E+2

f Decimal floating point 392.65 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o Signed octal 610 s String of characters sample u Unsigned decimal integer 7235 x Unsigned hexadecimal integer 7fa

X Unsigned hexadecimal integer (capital letters) 7FA p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to stdout.

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number)

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after de decimal point. For g and G specifiers: This is the maximum number of

significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

arg

An object representing the variable arguments list. It shall have already been initialized by the va_start macro defined in <cstdarg>.

Return Value On success, the total number of characters written is returned. On failure, a negative number is returned.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

/* vprintf example */ #include <stdio.h> #include <stdarg.h> void WriteFormatted (char * format, ...) { va_list args; va_start (args, format); vprintf (format, args); va_end (args); } int main () { WriteFormatted ("Call with %d variable argument.\n",1); WriteFormatted ("Call with %d variable %s.\n",2,"arguments");

18 19

return 0; }

The example illustrates how the WriteFormatted can be called with a different number of arguments, which are on their turn passed to the vprintf function, showing the following output: Call with 1 variable argument. Call with 2 variable arguments.

See also vfprintf Write formatted variable argument list to stream (function )

vsprintf Print formatted variable argument list to string (function )

printf Print formatted data to stdout (function )

vsprintf function <cstdio>

int vsprintf (char * str, const char * format, va_list arg );

Print formatted variable argument list to string

Writes into the array pointer by str a C string consisting in format with its format tags expanded to the values of the argument list arg formatted appropiately. This function behaves exactly as sprintf except that the variable argument list is passed as a va_list instead of a succession of arguments, which becomes specially useful when the argument list to be passed comes itself from a variable argument list in the calling function. vsprintf does not call the va_end macro.

Parameters str

Array of char elements where the resulting string is to be stored. format

C string that contains the text to be written to the str. It can optionally contain embedded format tags that are substituted by the values specified in the arg variable argument list and formatted as requested. The format tags follow this prototype: %[flags][width][.precision][length]specifier

Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument: specifier Output Example c Character a

d or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character

3.9265e+2

E Scientific notation (mantissa/exponent) using E character

3.9265E+2

f Decimal floating point 392.65 g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o Signed octal 610 s String of characters sample u Unsigned decimal integer 7235 x Unsigned hexadecimal integer 7fa X Unsigned hexadecimal integer (capital letters) 7FA p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write a % sign. The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

width description

(number) Minimum number of characters to be printed. If the value to be

printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after de decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

arg

An object representing the variable arguments list. It shall have already been initialized by the va_start macro defined in <cstdarg>.

Return Value On success, the total number of characters written is returned. On failure, a negative number is returned.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

/* vsprintf example */ #include <stdio.h> #include <stdarg.h> void PrintFError (char * format, ...) { char buffer[256]; va_list args; va_start (args, format); vsprintf (buffer,format, args); perror (buffer); va_end (args); } int main () { FILE * pFile; char szFileName[]="myfile.txt"; int firstchar = (int) '#'; pFile = fopen (szFileName,"r"); if (pFile == NULL) PrintFError ("Error opening '%s'",szFileName); else { // file successfully open fclose (pFile); } return 0; }

In this example, if the file myfile.txt does not exist, perror is called to show an error message similar to: Error opening file 'myfile.txt': No such file or directory

See also vfprintf Write formatted variable argument list to stream (function )

vprintf Print formatted variable argument list to stdout (function )

sprintf Write formatted data to string (function )

printf Print formatted data to stdout (function )

EOF

constant <cstdio>

End-of-File

It is a macro constant definition. It expands to a negative integral constant expression. It is used as the value returned by several <cstdio> functions to indicate failure, either because the End-of-File has been reached in a reading operation or because an error happened.

See also feof Check End-of-File indicator (function)

ferror Check error indicator (function)

FILENAME_MAX constant <cstdio>

Maximum length of file names

This macro constant expands to an integral expression corresponding to the size needed for an array of char elements to hold the longest file name string allowed by the system. Or, if the system imposes no such restriction, it is set to the recommended size for character arrays intended to hold any file name.

NULL constant <cstdio>

Null pointer

This macro expands to a null pointer constant. A null pointer is generally used to signify that a pointer does not point to any object. In C++, NULL expands either to 0 or 0L.

TMP_MAX constant

<cstdio>

Number of temporary files

This macro expands to the minimum number of unique temporary file names that are granted to be possible to generate using tmpnam or tmpfile.

FILE type

<cstdio>

Object containing information to control a stream

This type of object identifies a stream and contains the information needed to control it, including a pointer to its buffer, its position indicator and all its state indicators. FILE objects are usually created by a call to either fopen or tmpfile, which both return a reference to one of these objects. The content of a FILE object is not meant to be read from outside the functions of the cstdio library; In fact, its main purpose is to be referenced as an argument in all stream-involving functions of this library to identify the stream to be affected. Its memory allocation is automatically performed by either fopen or tmpfile, and is the responsibility of the library to free the resources once the stream has been closed using fclose or other means. On inclusion of the cstdio header file, three objects of type FILE * (pointer to FILE)are automatically created. These are associated with the standard input, output and error streams, and can be accessed respectively through the pointers stdin, stdout and stderr.

Example 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16

#include <stdio.h> int main() { FILE * pFile; char buffer [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { while ( ! feof (pFile) ) { if ( fgets (buffer , 100 , pFile) != NULL ) fputs (buffer , stdout); }

17 18 19 20

fclose (pFile); } return 0; }

This example reads the content of a text file called myfile.txt and sends it to the standard output stream.

See also fopen Open file (function )

fclose Close file (function)

fpos_t type

<cstdio>

Object containing information to specify a position within a file

This type of object is used to specify a position within a file. An object of this type is capable of specifying uniquely the position within a file. fpos_t objects are usually created by a call to fgetpos, which returns a reference to an object of this type. The content of a fpos_t is not meant to be read directly, but only to use its reference as an argument in a call to fsetpos.

size_t type

<cstdio>

Unsigned integral type

size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the <cstdio> header file (among others) as an unsigned integral type. In <cstdio>, it is used as the type of some parameters in the functions fread, fwrite and setvbuf, and in the case of fread and fwrite also as its returning type.

In all cases it is used as a type to represent the length or count in bytes of a specific buffer or string.

C File I/O and Binary File I/O

By Alex Allain

In this tutorial, you'll learn how to do file IO, text and binary, in C, using fopen, fwrite, and fread, fprintf,fscanf, fgetc and fputc.

FILE *

For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).

For example:

FILE *fp;

fopen To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

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

In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than asingle backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected. Your users, of course, do not need to do this! It's just the way quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are as follows:

r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)

Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer. Here's a simple example of using fopen:

FILE *fp; fp=fopen("c:\\test.txt", "r");

This code will open test.txt for reading in text mode. To open a file in a binary mode you must add a b to the end of the mode string; for example, "rb" (for the reading and writing modes, you can add the b either after the plus sign - "r+b" - or before - "rb+")

fclose When you're done working with a file, you should close it using the function

int fclose(FILE *a_file);

fclose returns zero if the file is closed successfully. An example of fclose is

fclose(fp);

Reading and writing with fprintf, fscanf fputc, and fgetc To work with text input and output, you use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. For example:

FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a time--this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you're at the very end of the file, you can't get a character value--in this case, fgetc will return "EOF", which is a constant that indicates that you've reached the end of the file. To see a full example using fgetc in practice, take a look at the example here. The fputc function allows you to write a character at a time--you might find this useful if you wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );

Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.

Binary file I/O - fread and fwrite For binary File I/O you use fread and fwrite. The declarations for each are similar:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions deal with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory. Let's look at one function to see how the notation works. fread takes four arguments. Don't be confused by the declaration of a void *ptr; void means that it is a pointer that can be used for any type variable. The first argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each element of the array; it is in bytes. For example, if you have an array of characters, you would want to read it in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you have a variable int x; you can get the size of x with sizeof(x);. This usage works even for structs or arrays. E.g., if you have a variable of a struct type with the name a_struct, you can use sizeof(a_struct) to find out how much memory it is taking up. e.g.,

sizeof(int);

The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array, you want to read no more than 100 elements, so you pass in 100. The final argument is simply the file pointer we've been using. When fread is used, after being passed an array, fread will read from the file until it has filled the array, and it will return the number of elements actually read. If the file, for example, is only 30 bytes, but you try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, use the feof function, which accepts a FILE pointer and returns true if the end of the file has been reached. fwrite is similar in usage, except instead of reading into the memory you write from memory into a file. For example,

FILE *fp;

fp=fopen("c:\\test.bin", "wb"); char x[10]="ABCDEFGHIJ"; fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);