Use
fwrite(buffer, 1, length, file);
This will only write as much characters as you acutally received. If the extra \0
are part of the packet it will be written, otherwise not.
If you are receiving the \0
characters as part of the packet but you don't want to write them, then you'd have to do this:
fwrite(buffer, 1, strlen(buffer), file);