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 char
s - how is it possible to store int
s in a char
array ?
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 achar
, except for the case when it returnsEOF
, 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 (ifchar
is an unsigned type - something the C and C++ standards support equally withchar
being a signed type that can be-1
).