Reading and writing characters in C.


Source listing
//------------------------------------------------------
// File: Code600_FileIO.cpp
// Purpose: Demonstration of character I/O in ANSI Standard C
// Programming Language: C
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#include <stdio.h>

int main(void)
{
    FILE *fptr;  // pointer to FILE
    char ch;

    //-----------------------------------------------
    //  Writing characters to a file
    //  I/O function:  int fputc(int ch, File *fptr)
    //-----------------------------------------------
    // Open the file for writing
    fptr=fopen("textfile.txt","w");

    // Write characters entered from the keyboard till user presses Enter
    while ( (ch = getc(stdin)) != '\n')
        fputc(ch, fptr);

    // Close the file
    fclose(fptr);

    //-----------------------------------------------
    //  Reading characters from a file
    //  I/O function:  int fgetc(File *fptr)
    //-----------------------------------------------
    if( (fptr = fopen("textfile.txt","r")) == NULL)
    {
        printf("Can't open textfile.txt.\n");
        return 0;
    }
    while ( (ch = fgetc(fptr)) != EOF)
        printf("%c", ch);
    fclose(fptr);
    return 0;
}