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)

The opened file is automatically closed by the C runtime when the program exits, although usually one would use fclose to close it.


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer