Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "FILE *fp, *fopen();" do?

Tags:

c

unix

On page 182 of The UNIX Programming environment the code for efopen is listed as follows:

FILE *efopen(file, mode)    /* fopen file, die if can't */
    char *file, *mode;
{
    FILE *fp, *fopen();
    extern char *progname;

    if ((fp = fopen(file, mode)) != NULL)
        return fp;
    fprintf(stderr, "%s: can't open file %s mode %s\n",
        progname, file, mode);
    exit(1);
}

What does the line FILE *fp, *fopen(); do?

My reading is that it declares a variable fp which is a pointer to a FILE and a function fopen which returns a pointer to a FILE.

If so: Why is fopen forward declared within the function body? How come we don't declare its arguments?

like image 572
chromy Avatar asked Jan 28 '23 14:01

chromy


1 Answers

It creates a local variable named fp (of type FILE *), and forward declares an external function named fopen (with a signature of FILE *fopen()).

The lack of parameters in the fopen function declaration in C doesn't mean the function takes zero parameters (that function signature would be FILE *fopen(void)). Instead, the lack of parameters means the function has unspecified parameters (unspecified in quantity and unspecified in type).

This is a really old form of C that would be more idiomatically written in modern C as:

#include <stdio.h>   // fopen() and fprintf()
#include <stdlib.h>  // exit()
#include <string.h>  // strerror()
#include <errno.h>   // errno

extern char *progname;

FILE *efopen(const char *file, const char *mode) {
    FILE *fp = fopen(file, mode);
    if (fp) return fp;

    fprintf(stderr, "%s: can't open file %s in mode %s: %s\n",
            progname, file, mode, strerror(errno));
    exit(1);
}
like image 63
Cornstalks Avatar answered Jan 30 '23 05:01

Cornstalks