How to write 0x00 to a file

I am writing some kind of application that will communicate (write only) with my custom USB serial device. This is a Cocoa application (OS X) and the part associated with this entry is POSIX-style.

I solved basically everything, but had problems with the NULL character (0x00).

For example, it allows me to say that I need to write 5 characters to a file.

My code is as follows:

char stringAsChar[5]; stringAsChar[0] = 0x77; stringAsChar[1] = 0x44; stringAsChar[2] = 0x00; //here is an problem stringAsChar[3] = 0x05; stringAsChar[4] = 0xFF; ... fputs(stringAsChar, file); // write to file 

Each character in the specified index represents data for some registers in the target device.

The problem occurs when the stream includes the 0x00 character, which I need to have as data, the record stops there (0x00 is interpreted as stopping the stream).

How to overcome this problem?

+4
source share
3 answers

fputs works with NUL terminated strings. If you want to write NUL to a file, you can use fwrite instead:

 noOfBytesWritten = fwrite(stringAsChar, 1, noOfBytesToWrite, file); 
+3
source

Try using fwrite instead. It allows you to specify the number of bytes written to the stream. Or flip characters and use fputc .

+4
source

fputs() works with null characters. You cannot have NULL embedded in a C string because it is a terminator. You can use fputc() to write a NULL byte to a file.

+3
source

Source: https://habr.com/ru/post/1481947/


All Articles