How to detect EOF in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>

void read_file(char filename[]) {
    FILE* fp = fopen(filename, "r");

    if (fp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }

    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }
    
    fclose(fp);
}


int main()
{
    char filename[32] = "d:\\data.txt";
    
    read_file(filename);

    return 0;
}




/*
run:

C is a general-purpose programming language.
It was created in the 1970s by Dennis Ritchie and remains very widely used and influential.

*/

 



answered Jun 19, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

void read_file(char filename[]) {
    FILE* fp = fopen(filename, "r");

    if (fp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }
    
    int ch = getc(fp);
    while (ch != EOF) {
        putchar(ch);
        ch = getc(fp);
    }
    
    fclose(fp);
}


int main()
{
    char filename[32] = "d:\\data.txt";
    
    read_file(filename);

    return 0;
}




/*
run:

C is a general-purpose programming language.
It was created in the 1970s by Dennis Ritchie and remains very widely used and influential.

*/

 



answered Jun 19, 2024 by avibootz
...