First off, this isn't homework. Just trying to understand why I'm seeing what I'm seeing on my screen.
The stuff below (my own work) currently takes an input file and reads it as a binary file. I want it to store each byte read in an array (for later use). For the sake of brevity the input file (Hello.txt) just contains 'Hello World', without the apostrophes.
int main(int argc, char *argv[]) {
FILE *input;
int i, size;
int *array;
input = fopen("Hello.txt", "rb");
if (input == NULL) {
perror("Invalid file specified.");
exit(-1);
}
fseek(input, 0, SEEK_END);
size = ftell(input);
fseek(input, 0, SEEK_SET);
array = (int*) malloc(size * sizeof(int));
if (array == NULL) {
perror("Could not allocate array.");
exit(-1);
}
else {
input = fopen("Hello.txt", "rb");
fread(array, sizeof(int), size, input);
// some check on return value of fread?
fclose(input);
}
for (i = 0; i < size; i++) {
printf("array[%d] == %d\n", i, array[i]);
}
Why is it that having the print statement in the for loop as it is above causes the output to look like this
array[0] == 1819043144
array[1] == 1867980911
array[2] == 6581362
array[3] == 0
array[4] == 0
array[5] == 0
array[6] == 0
array[7] == 0
array[8] == 0
array[9] == 0
array[10] == 0
while having it like this
printf("array[%d] == %d\n", i, ((char *)array)[i]);
makes the output look like this (decimal ASCII value for each character)
array[0] == 72
array[1] == 101
array[2] == 108
array[3] == 108
array[4] == 111
array[5] == 32
array[6] == 87
array[7] == 111
array[8] == 114
array[9] == 108
array[10] == 100
? If I'm reading it as a binary file and want to read byte by byte, why don't I get the right ASCII value using the first print statement?
On a related note, what happens if the input file I send in isn't a text document (e.g., jpeg)?
Sorry is this is an entirely trivial matter, but I can't seem to figure out why.