how to insert a \0 to a binary file in C
I have to insert a bunch of chars to a binary file.
In order to do that I use fwrite. After that, I would like to put a \0
.
I am not sure how to do it.
const unsigned char *my_word; /*my_word has no \0 at the end*/
fwrite(my_word, my_word_length_in_bytes, 1, my_file);
Can you please help开发者_运维知识库?
Thanks.
You can use the following:
fputc(0, my_file);
You need to have your buffer my_word alocated with +1, then
my_word[my_word_length_in_bytes]=0;
fwrite(my_word, my_word_length_in_bytes+1, 1, my_file);
`fputc('\0', my_file);` will do it for you
An old trick is to use an empty null-terminated string
fwrite("", 1, 1, my_file);
You can either concatenate a '\0' character at the end of word
before you actually write it into your file (best solution imho) or do a second fwrite with a 0x00 byte (which is ASCII code for '\0').
精彩评论