Search code examples
cfilenull-terminatedraw-data

Writing raw data to a file


I have an uint8_t array of raw data that I want to write to a file (I have it's length)

The problem is that because I'm dealing with raw data there might be a 0x00 (aka null terminator) somewhere, meaning fputs is not reliable, the obvious alternative is to have a loop to use fputc() but is there a way i can do it without that?

Is there say a function that takes a pointer and a size and writes that amount of data from the pointer's location to the file?


Solution

  • In addition to the problem with null-character, there is problem reading binary data when file is opened in text mode (for example fgets stops when it encounters new line or 0x0A and 0x1A character in Windows)

    Open the file in binary mode instead, and use fread/fwrite

    FILE *fout = fopen("test.bin", "wb");
    

    And use fwrite and fread

    Reference