The standard C library includes a number of functions for handling I/O streams. These functions put certain constraints on the values of their
parameters. The constraints include the following:
- The value for the
FILE*
-typed parameter may not be NULL
- The third argument of
fseek
must be either of SEEK_SET
, SEEK_END
, or SEEK_CUR
Failing to pass correctly constrained parameters renders them invalid and will result in undefined behavior.
#include <stdio.h>
size_t get_file_size() {
FILE *f = fopen("example_file.txt", "r");
// `f` may be NULL if `fopen` fails.
fseek(f, 0L, SEEK_END); // Leads to undefined behavior, if `f` is NULL.
size_t size = ftell(f); // Leads to undefined behavior, if `f` is NULL.
fclose(f);
return size;
}