Reputation: 425
I'm trying to understand how to read and write in C. Would this store entries from the binary file into the buffer until the end of file.
unsigned char *buffer = (char*) malloc (sizeof(char) * SIZE);
FILE *file = fopen(FILEPATH, "rb");
if(file == NULL){
//error
} else {
while(!feof(file)){
fread(&buffer, SIZE*sizeof(char), 1, file);
// Print out buffer (should be different everytime assume I have different numbers in the file)
}
}
Or would I have to use fseek somewhere there?
Vice-versa to write something to a document would this work? Thanks
unsigned char *buffer = (char*) malloc (sizeof(char) * SIZE);
FILE *file = fopen(FILEPATH, "wb");
for(int i=0; i<SIZE; i++){
// put something into buffer based on i
fwrite(&buffer, SIZE*sizeof(char), 1, file);
}
Upvotes: 2
Views: 88
Reputation: 400109
No, that would probably crash. :)
buffer
, which is already a pointer: this is wrong. Just pass buffer
directly to fread()
. The value of buffer
and &buffer
are only the same when buffer
is an array; not when it's allocated on the heap like your is.feof()
, rely on the return value of fread()
.malloc()
in C.sizeof (char)
, that's always 1 so it adds nothing.Upvotes: 3