I'm trying to read unknown length binary file into buffer chunks without using the functions like lseek()
,fseek
.
- I have used struct buffer that has 1024 bytes at once. when reading file larger than 1012 bytes it will allocate several buffers. However, when it encounters the last chunk it will definitely have less or equal to 1024 bytes.
Thus, i try to count the length of the last chunk so that I can read last chunk up until the
eof
but i am kind of confused with how to implement this.
Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
typedef struct Buffer{
unsigned char data[1012];
struct Buffer *next; //12 bytes
}Buffer;
void mymemcpy(void *dest, void *src, size_t length){
Buffer *buffer_toFill = (Buffer *)dest;
Buffer *buffer_toAdd = (Buffer *)src;
int a = 0;
for(int i = 0; i < length; i++){
buffer_toFill->data[i] = buffer_toAdd->data[i];
}
}
Buffer* add_buffer_front(Buffer *head, Buffer *read_buffer, int size){
Buffer *new_buffer = malloc(sizeof(Buffer));
mymemcpy(new_buffer, read_buffer, size);
if(head != NULL){
new_buffer->next = head;
}
return new_buffer;
}
void display_List(Buffer *head, size_t length){
Buffer *current = head;
while(current != NULL){
for(int i = 0; i < length; i++){
printf("%02X",(unsigned)current->data[i]); //this shows different value compare with xxd <filename>
//printf("%c", current->data[i]);
}
Buffer *prev = current;
free(prev);
current = current->next;
}
}
int main(int argc, char **argv){
FILE *fd;
Buffer *head_buffer = NULL;
int file_length = 0;
int eof_int = 1;
if(argc != 2){
printf("Usage: readFile <filename>\n");
return 1;
}
fd = fopen(argv[1], "rb");
while(eof_int != 0){
Buffer *new_buffer = malloc(sizeof(Buffer));
eof_int = fread(new_buffer, sizeof(Buffer)-12, 1, fd);
if(eof_int == 0){
//size_t length
//
//
head_buffer = add_buffer_front(head_buffer, new_buffer, length);
file_length += length;
}else{
head_buffer = add_buffer_front(head_buffer, new_buffer, (sizeof(new_buffer->data)));
file_length += (sizeof(new_buffer->data));
}
}
display_List(head_buffer, file_length);
fclose(fd);
return 0;
}