Reputation: 489
I am trying to read from a Binary file called "binary.bin" which has the content of "this". I was expecting it to give me the ASCII values of "t", "h", "i", "s" respectively, but it's giving me 5 zeroes.
void bin_byte_by_byte(char *filename) {
FILE *fptr;
unsigned long len;
int *buffer;
fptr = fopen(filename, "rb");
if(!fptr) {
printf("error: file does not exist");
return;
}
// get file lenght - create a function to this
fseek(fptr, 0, SEEK_END);
len = ftell(fptr);
fseek(fptr, 0, SEEK_SET);
buffer = (int*)malloc(sizeof(int) * len);
if(!buffer) {
printf("error: unable to allocate memory");
fclose(fptr);
return;
}
fread(&buffer, sizeof(buffer), len, fptr);
printf("len = %d\n", len);
for(int i = 0; i < len; i++) {
printf("%d ", buffer[i]);
}
if(fclose(fptr) != 0) {
printf("File did not close as expected");
}
free(buffer);
}
Upvotes: 0
Views: 305
Reputation: 550
Your file is supposed to be binary but it seems that you pass a text file to your program. The file is 5 bytes which suits to the content "this". If you read this file as binary, maybe it makes sense to read bytes and not ints. If you want to read bytes into an int array, you should read byte-wise and store each byte into one position of your int array.
In the program you've listed there are few mistakes.
buffer = (int*)malloc(sizeof(int) * len);
the line above creates an array of 5 ints. So, it takes 20 bytes (assuming 32-bit platform).
Then you read from the file:
fread(&buffer, sizeof(buffer), len, fptr);
This line reads 20 bytes from the file although it is only 5 bytes long. Also, you pass address of the pointer variable but you need to pass the address of the buffer. So, it should be just buffer and not &buffer
But the main point is here that into buffer[0] goes 4 bytes. So, 't', 'h', 'i', 's' go to the first element of buffer.
So, either you can use char for the array type or you read byte-by-byte and store each byte into a separate element of the buffer
Upvotes: 1