How to read an entire binary file all at once in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    long file_size;
    char *buffer;
    size_t rv;

    FILE *fp;
    fp = fopen("d:\\data.bin","rb");
    if (!fp) {fputs("File open error",stderr); return 1;}

    // get the file size
    fseek (fp , 0 , SEEK_END);
    file_size = ftell (fp);
    // sets fp to the beginning of the file
    rewind (fp);

    // allocate memory to contain all the file + 1 for null:
    buffer = (char*) malloc (sizeof(char) * file_size + 1);
    if (!buffer) {fputs ("Memory allocation error",stderr); return 2;}

    // copy all the file into the buffer:
    rv = fread(buffer, 1, file_size, fp);
    if (rv != file_size) {fputs("File reading error",stderr); return 3;}

    // put null at the end of string
    buffer[file_size] = '\0';
    printf("file content = %s", buffer);

    fclose(fp);
    free(buffer);
 
    return 0;
}

/*
run: (the content of d:\\date.bin)

file content = C Programming

*/


answered Oct 20, 2014 by avibootz

Related questions

1 answer 241 views
5 answers 442 views
2 answers 340 views
2 answers 267 views
1 answer 174 views
1 answer 560 views
1 answer 180 views
...