-1

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.

JustAsking
  • 13
  • 1
  • 1
  • 1
    If you write binary data, how do you know that ',' is your separator or part of the data? – Devolus Mar 31 '21 at 16:12
  • _"binary data separated by ',' "_: that is somewhat contradictory. [Edit] and explain more thoroughly what you're trying to achieve. Also read this: [ask] – Jabberwocky Mar 31 '21 at 16:16
  • 1
    If you're able to resolve the problem using the stdio functions `fopen`, `fwrite` and `fread`, then you should be able to resolve it with the posix functions `open`, `creat`, `read` and `write` which are pretty similar.. – Jabberwocky Mar 31 '21 at 16:20
  • 1
    read and write ***are*** for binary data. (because there isn't binary data and not-binary data. there's just data) – user253751 Mar 31 '21 at 16:23
  • Hello and welcome to StackOverflow! Have you looked at the documentation for those functions? – Daniel Walker Mar 31 '21 at 16:49
  • It is either all binary, or none of it is binary. You cannot have _"comma separated binary data"_ without some sort of encoding, and what would be the point? All data stored is _binary_, it is a matter of what it _represents_. The binary sequence 0010 1100 for example represents the value 44 decimal, but it also represents ASCII comma. The only way to have comma-separated binary is if you could guarantee that your binary did not contain 0010 1100. Or as I say use some sort of encoding - not raw binary. – Clifford Mar 31 '21 at 17:02

1 Answers1

3

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.

Clifford
  • 88,407
  • 13
  • 85
  • 165