How to read an unknown number of bytes from an input stream that may contain null characters?

StackOverflow https://stackoverflow.com/questions/14197976

  •  13-01-2022
  •  | 
  •  

Pergunta

I'm having some trouble reading an unknown amount of bytes (raw data, may contain NULLs) from a device using c in Linux. How can I read the device for "as long as it's ready to be read"? (hopefully without reading 1 byte at a time).

Foi útil?

Solução

Well if you're using read you'll either block if there's no data, or succeed if there was data to read. If there was data to read you'll get either the amount you wanted, or an amount less if there's no more to read. Look at the return value of read to determine how much you have. You could make it non-blocking but the approach of checking reads return value holds true regardless.

Just chunk through the data in whatever size chunks you want to deal with, one character at a time, or more, if you're more aware of the kind of bursts of data you'll have.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top