wzsun
wzsun

Reputation: 425

Basic read/write clarification in C

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

Answers (1)

unwind
unwind

Reputation: 400109

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.

Upvotes: 3

Related Questions