×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Value of EOF in c programming language

What is EOF in C?

EOF indicates the END of File. It is a predefined MACRO with the value of -1 which means EOF is not a character. The EOF is returned through the function which is going to be read the content from the file.

C program to print the value of EOF

Consider the below program which is printing the value of EOF.

#include <stdio.h>

int main()
{
    printf("Value of \"EOF\" is = %d\n", EOF);
    return 0;
}

Output

Value of "EOF" is = -1

Use EOF to run through a text file in C

Consider the below program which is reading the characters from a text file till EOF (end of file).

There is a file "text1.txt" containing "Hello World"

#include <stdio.h>

int main()
{
    FILE* fp;
    int ch;

    fp = fopen("text1.txt", "r");
    if (fp == NULL) {
        printf("Error in file opening...\n");
        return -1;
    }

    printf("Content of the file:\n");
    /*here we are using infinite loop to print value of 
	EOF, loop will be terminate as we got EOF*/
    while (1) {
        ch = getc(fp); //read one character
        printf("%c [%d],", ch, ch);
        if (ch == EOF) {
            break; //terminate loop
        }
    }

    //close the file
    fclose(fp);

    return 0;
}

Output

H [72],e [101],l [108],l [108],o [111], [32],W [87],o [111],r [114],l [108],d [100], 
 [10],� [-1],
EOF in C programming Language

Reference: Definition of EOF




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.