Demonstrates the fopen() function. - C File

C examples for File:File Read

Description

Demonstrates the fopen() function.

Demo Code

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
   FILE *fp;//from w w  w  .jav  a2s .com
   char ch, *filename="text.txt", mode[4];

    while (1)
    {
        printf("\nEnter a mode (max 3 characters): ");
        gets_s(mode);

        /* Try to open the file. */

        if ( (fp = fopen( filename, mode )) != NULL )
        {
            printf("\nSuccessful opening %s in mode %s.\n",
                    filename, mode);
            fclose(fp);
            puts("Enter x to exit, any other to continue.");
            if ( (ch = getc(stdin)) == 'x')
                break;
            else
                continue;
        }
        else
        {
            fprintf(stderr, "\nError opening file %s in mode %s.\n",
                    filename, mode);
            puts("Enter x to exit, any other to try again.");
            if ( (ch = getc(stdin)) == 'x')
                break;
            else
                continue;
        }
    }
    return 0;
}

Result


Related Tutorials