getc return value stored in a char variable

4.5k views Asked by At

On this Wikipedia page there is a sample C program reading and printing first 5 bytes from a file:

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

int main(void)
{
    char buffer[5] = {0};  /* initialized to zeroes */
    int i;
    FILE *fp = fopen("myfile", "rb");

    if (fp == NULL) {
        perror("Failed to open file \"myfile\"");
        return EXIT_FAILURE;
    }


    for (i = 0; i < 5; i++) {
        int rc = getc(fp);
        if (rc == EOF) {
            fputs("An error occurred while reading the file.\n", stderr);
            return EXIT_FAILURE;
        }
        buffer[i] = rc;
    }

    fclose(fp);

    printf("The bytes read were... %x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);

    return EXIT_SUCCESS;
}

The part I don’t understand is that it uses getc function which returns an int and stores it in an array of chars - how is it possible to store ints in a char array ?

3

There are 3 answers

0
Mats Petersson On BEST ANSWER

Techically, C allows you to "shorten" a variable by assigning it to something that is smaller than itself. The specification doesn't say EXACTLY what happens when you do that (because of technicalities in some machines where slightly weird things happens), but in practice, on nearly all machines that you are likely to use unless you work on museum pieces or some very special hardware, it simply acts as if the "upper" bits of the larger number has been "cut off".

And in this particular case, getc is specifically designed to return something that fits in a char, except for the case when it returns EOF, which often has the value -1. Although quite often, char may well support having the value -1 too, but it's not guaranteed to be the case (if char is an unsigned type - something the C and C++ standards support equally with char being a signed type that can be -1).

0
Rahul Tripathi On

Check this out:-

If the integer value returned by getc() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.

0
DoxyLover On

Yes, getc() returns an integer. However, except for the special return value EOF, the returned value will always be within the range of a char (-128 to 127 on a 2's compliment machine with default signed chars).

Therefore, after checking for EOF, it is always safe to transfer the value to a char variable without data loss.