2

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);
}
wzsun
  • 295
  • 2
  • 7
  • 15
  • You probably should remove the `SIZE*sizeof(char)` and use only `sizeof(char)`, as you are reading/writing `SIZE` number of characters from/to the file. – MD Sayem Ahmed Oct 21 '13 at 08:48
  • Yea I just noticed that as well and changed it – wzsun Oct 21 '13 at 08:49
  • 1
    1) `sizeof(char)` is 1 by definition. 2) don't use `feof()` this way, use the return value from read/write instead. 3) don't cast the result from `malloc()` it is not needed and potentially dangerous. – joop Oct 21 '13 at 08:52

1 Answers1

3

No, that would probably crash. :)

  1. You're taking the address of 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.
  2. Don't use feof(), rely on the return value of fread().
  3. Don't cast the return value of malloc() in C.
  4. Don't scale allocations by sizeof (char), that's always 1 so it adds nothing.
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • Could you expand on how to use the return value to determine if it is the end of file? – wzsun Oct 21 '13 at 08:57
  • Lets say the size was 12 bytes, and I wanted to read it 1 byte at a time (which I think my code is doing). Every time it loops would fread return 1? and would fread keep progressing through the file and keep track of that? Would I have to put some counter? – wzsun Oct 21 '13 at 09:03
  • @joop I've been messing with `read()` and `write()` too much :p I couldn't edit my comment anymore, so I deleted it. – Filipe Gonçalves Oct 21 '13 at 09:49