Explain the END OF FILE (EOF) with a C Program



The End of the File (EOF) indicates the end of input.

After we enter the text, if we press CTRL+Z, the text terminates i.e. it indicates the file reached end nothing to read.

Algorithm

Refer to the algorithm given below for EOF.

Step 1: Open file in write mode. Step 2: Until character reaches end of the file, write each character in filepointer. Step 3: Close file. Step 4: Again open file in read mode. Step 5: Reading the character from file until fp equals to EOF. Step 5: Print character on console. Step 6: Close file.

Example

Following is the C program for End of File (EOF) ?

#include <stdio.h> int main(){    char ch;    FILE *fp;    fp=fopen("std1.txt","w"); //open the file in write mode    printf("enter the text then press cntrl Z:
"
);    while((ch = getchar())!=EOF) //reading char by char until it equals to EOF{       i.e. when u press ctrlZ the while loop terminates       putc(ch,fp);    }    fclose(fp);    fp=fopen("std1.txt","r");    printf("text on the file:
"
);    while ((ch=getc(fp))!=EOF) //reading the character from file until fp equals to EOF{       putchar(ch);    }    fclose(fp);    return 0; }

Output

When the above program is executed, it produces the following result ?

enter the text then press cntrl Z: This is the EOF demonstration example if your text typing is over press cntrlZ ^Z text on the file: This is the EOF demonstration example if your text typing is over press cntrlZ
Updated on: 2023-09-14T21:13:13+05:30

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements