Question: What are EOF, FOPEN_MAX and FILENAME_MAX Constants for and How Can we Use them in a C Program?

Answer: Each file how long it may be but ends. EOF character marks end of it. Many of I/O functions return EOF when they have reached end of the given file. The value chosen for EOF uses more bits than a character to prevent binary character values from being mistakenly interpreted as EOF. While performing reading and/or searching through a file we can read until reach end of the file i.e. until we encountered EOF character. EOF constant is defined in stdio.h. I included the fragment of code from stdio.h header for reference below

/* End of file character.
   Some things throughout the library rely on this being -1.  */
#ifndef EOF
# define EOF (-1)

Let’s see a simple C program to use EOF character

/* eof.c -- let's use EOF */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
    FILE *fp;
    int ch;
    /* open a stream for reading from a file */
    if (argc != 2) {
        perror("File Argument");
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        perror("File Open");
    /* read the file until EOF is reached */
    while ((ch = fgetc(fp)) != EOF)
        /* write the character to stdout */
    return 0;

Notice that above program reads file argument from the command line argument, opens the stream in read mode, then reads character by character from the stream and writes to the stdout which is by default terminal.


Let’s turn ours’ attention to question, how many files a program can have open at once? Though this is implementation dependent, but you are guaranteed of being able to open at least FOPEN_MAX no. of files simultaneously. This symbolic constant is also defined in stdio.h header.

Similarly, symbolic constant FILENAME_MAX, defined in stdio.h header, specifies how long a character array should be to hold the longest legal file name that the implementation supports. If there isn’t a practical limit on the length of a file name, then this value should recommend the valid size for such strings.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C Tutorials, go to C Tutorials.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.