Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write 0x00 into file

I'm writing some application which will communicate (write only) with my custom USB-serial device. It is Cocoa (OS X) application and part which is related to this writing is coded in POSIX style.

I have solved mostly all things but have issues with NULL (0x00) character.

For example lets says that I need to white 5 characters to a file.

My code is as follow:

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 at specified index represents data for some registers into target device.

The problem arise when stream include 0x00 character which i need to have as data, writing is stopped there (0x00 interpreted as stop of stream).

How to overcome this issue?

like image 714
mikikg Avatar asked Dec 27 '22 03:12

mikikg


2 Answers

Try using fwrite instead. It lets you specify the amount of bytes written to the stream. Or loop over your characters and use fputc.

like image 68
DrummerB Avatar answered Jan 05 '23 23:01

DrummerB


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

noOfBytesWritten = fwrite(stringAsChar, 1, noOfBytesToWrite, file);
like image 27
Klas Lindbäck Avatar answered Jan 05 '23 22:01

Klas Lindbäck