C - hex value 0x00 not being written to file

3643 views c

I am writing a program and I want to write some hex addresses to the file. The problem is that when I hexdump -C temp the file, I only see bc ab and the \x00 were not written to the file for some reason I don't understand. Maybe they were recognized as EOF characters? Any help is really appreciated.

File *file;
char *buffer, *ptr;

ptr = buffer;
*(ptr++) = '\xbc';
*(ptr++) = '\xab';
*(ptr++) = '\x00';  // problem
*(ptr++) = '\x00';

file = fopen("temp", "w");
if (file == NULL) {
  fprintf(stderr, "Opening file failed.\n");

fprintf(file, "%s", buffer);

answered question

use open mode "wb"

also consider using fwrite rather than fprintf if you don't want it to stop at the first \x00

The value zero (\x00) is a special value (NULL) that is typically used to indicate the end of a string.

1 Answer


You tried to write null characters with fprintf's %s. Null character is the string terminator. It won't be written that way. Use fwrite or fputc.

posted this

Have an answer?


Please login first before posting an answer.