C Programming Tutorial
Computer Tutorial

Writing to a File



Writing to a File

The C I/O system defines two equivalent functions that output a character: putc( ) and fputc( ). (Actually, putc( ) is usually implemented as a macro.) The two identical functions exist simply to preserve compatibility with older versions of C. This book uses putc( ), but you can use fputc( ).
The putc( ) function writes characters to a file that was previously opened for writing using the fopen( ) function.
The putc( ) function prototype :
int fclose(FILE *fp);
int putc(int ch, FILE *fp) ;

where fp is the file pointer returned by fopen( ), and ch is the character to be output. The file pointer tells putc( ) which file to write to. Although ch is defined as an int, only the low-order byte is written.

If a putc( ) operation is successful, it returns the character written. Otherwise, it returns EOF.
our sample file-copy program is capable of copying only text files. To copy files with extension .EXE or .COM, we need to open the files in binary mode, a topic that would be dealt with in sufficient detail in a later section.