coding programming in C

I’m attempting with this post to document my progress through learning C programming language. It’s without a doubt a tough first language but I like a challenge. The main aim with this post is to use it as motivation to look back on how far I’ve come and to not give up when I inevitably cannot figure out why my bloody program isn’t functioning or more commonly – why I’m not functioning!

The secondary aim is to provide some value to you, so if you find any of this useful, I’m glad – go make someone smile.

16/07/2020: EOF – End of File

Getting to grips with EOF (End of File) was difficult for me. Here’s my notes;

EOF is NOT a char, a value at the end of a file or a value that could be within a file.

EOF is a macro defined as an int with a negative value.

It is normally returned by functions that perform read operations, usually to tell the compiler there was either an error or end of input.


Since the return value of EOF is negative integer, we need the variable we are storing the value in, to be able to store a negative integer.
Integers are larger than characters in C, therefore a negative int could never be the same value as a char.

Depending on how the compiler deals with char’s, it could be signed or unsigned, the EOF stored in the variable could match perfectly in the case of a signed char but won’t match in the case of a unsigned char. If the EOF isn’t stored correctly in the variable, then when your program is looking for the EOF, it will never find it and go into an infinite loop. The program below demonstrates this.

You can look up ‘char to int promotion’ and also ‘binary twos complement’ for more information.

Also run the below program in C and comment out either line 9 or 10. The two results will give you clarity as to why using the ‘char’ to store the EOF is a bad idea.

//Make a file in the same folder as this code called myfile.txt and write something inside it
#include <stdio.h>

int main(void)
    FILE *fp;

    //comment out, two of the three below lines... either char or int and test the difference between
    unsigned char c;
    signed char c;
    int c;

    if ((fp = fopen("myfile.txt", "rb")) == NULL)
        return 0;

    while ((c = fgetc(fp)) != EOF)

    return 0;

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment