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) #endif
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"); exit(EXIT_FAILURE); } fp = fopen(argv[1], "r"); if (fp == NULL) { perror("File Open"); exit(EXIT_FAILURE); } /* read the file until EOF is reached */ while ((ch = fgetc(fp)) != EOF) /* write the character to stdout */ putchar(ch); 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.
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for Computer Science Internship
- Practice BCA MCQs