Open a file in C

This example program demonstrates opening a file for reading. It uses fopen to open the file. The file used is fopen.c, which is the source file for the program. If the program cannot open the file, it prints an error message on the standard error stream.

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

int main (int argc, char ** argv)
{
    FILE * f;

    f = fopen ("fopen.c", "r");
    if (! f) {
        fprintf (stderr, "Can't open 'fopen.c': %s\n",
                 strerror (errno));
        exit (EXIT_FAILURE);
    }

    return 0;
}

Download it here.

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer