File Input/Output Functions

The classic functions for reading from and writing to files are declared in the header file stdio.h . In the descriptions that follow in Table 1-23, fp designates the file pointer. Those functions that have no parameter with the file pointer type read from stdin or write to stdout.

Reading and writing characters and strings

Table 1-23.  Character read and write functions



Write a character

int fputc( int c, FILE *fp );
int putc( int c, FILE *fp );
int putchar( int c );

Read a character

int fgetc( FILE *fp );
int getc( FILE *fp ); 
int getchar( void );

Put back a character

int ungetc( int c, FILE *fp );

Write a line

int fputs( const char *s, FILE *fp ); 
int puts( const char *s );

Read a line

char *fgets( char *s, int n, FILE *fp );
char *gets( char *buffer );

For each of these input/output functions, there is also a corresponding function for wide-oriented access. The wide functions are declared in the header file wchar.h (*). Their names are formed with wc (for wide character) in place of c (for character), or with ws (for wide string) in place of s (for string).

Block read and write functions

The following file access functions can be used to read or write a block of characters:

size_t fwrite( const void *buf, size_t sz, size_t n, FILE *fp );

Writes n objects of length sz from the buffer addressed by buf to the file.

size_t fread( void *buffer, size_t sz, size_t n, FILE *fp );

Reads up to n objects of ...

Get C Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.