Home > Net >  How to write a file to a buffer memory in C
How to write a file to a buffer memory in C

Time:07-19

So i got my function here that works to write back any file

    int write_file(FILE *f_write) {

    // Temp variables
    FILE *img = fopen("test.pdf", "wb");
    unsigned char buffer[255];
    
    while ( (bytes_read = fread(buffer, 1, sizeof(buffer), f_write) ) > 0) {
        fwrite(buffer, 1, bytes_read, img);
    }

    fclose(img);
    return 1;
}

So this works perfecly ive tried with pnj / pdf / jpg etc..

But now i want to stock what ive writen in the memory so i can use it later and not write right away

like an array of uint8_t (maybe) that will contain all the bytes ive writen and that i can send later with sockets to my server and store the file

no idea how to do it

Or maybe i'm making it too complicated and i can just

send(client_socket, FILE, sizeof(FILE), 0); ?

CodePudding user response:

One way to do it would be to create a buffer that exactly fits the size of the file. In order to do so, you can write a function to get the size of an openned file like so:

size_t get_file_size(FILE *f)
{
    size_t pos = ftell(f); // store the cursor position
    size_t size;

    // go to the end of the file and get the cursor position
    fseek(f, 0L, SEEK_END);
    size = ftell(f);

    // go back to the old position
    fseek(f, pos, SEEK_SET);
    return size;
}

Then create and fill your buffer:

FILE *f = fopen("your_file", "r");
size_t size = get_file_size(f);
char *buffer = malloc(size);

if (fread(buffer, 1, size, f) != size) { // bytes read != computed file size
    // error handling
}

// use your buffer...

// don't forget to free and fclose
free(buffer);
fclose(f);

It is worth mentioning that you should check if the file was opened correctly, and to check if you have enough memory to store the buffer (the one created with malloc).

  •  Tags:  
  • c
  • Related