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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With