Search code examples
cposixbinaryfilesfile-writing

How to write and read binary data to file in C with posix library using file descriptors?


I would like to write some binary data into file "something.dat" using functions write() and read(). I get file descriptor as argument. The goal is to write binary data separated by ',': data,data1,data2,data3 and then read it again from binary file. I am not allowed to use fopen(), fwrite() and fread().

I have searched for binary examples, but mostly all others examples are with file pointers or functions that are not a option. Can i get a simple example how to do this? I can do the rest myself.


Solution

  • The POSIX read()/write() functions are implicitly binary. Just write the data:

    uint8_t data[] = { 0x00, 0xFF, 0xDE } ;
    ssize_t written = write( fd, data, sizeof(data) ) ;
    

    It seems that you may be confused by the "b"/"t" open modes of fopen(). That is not relevant here - it is just binary. Even with the "t" (text) open mode only affects line-end translation and on platforms where the line-end convention is LF (such as Linux), it has no effect at all.

    The concept of comma-separated binary data in your "goal" is however flawed. Text files do not contain glyphs, they comprise of binary codes representing characters that the platform may render as glyphs - on a display for example.

    Comma is represented by the binary sequence 0010 1100 (44 decimal), so you cannot comma-separate binary data and distinguish the commas from any other binary data.