user997112
user997112

Reputation: 30635

Pipe a file of bytes to C++program, via Linux and read byte-by-byte?

Is there a way to pipe a file of (bytes- obviously) in to a C++ application on Linux. However, rather than just use getline() I would like to read each byte only once. For example I don't want to use getline() because it would read all the bytes up to the '\n' and then I would also have to re-read the bytes given to me via getline(), so the bytes are read twice. I would just like to "iterate" through each byte once.

What would be the best-performing technique, to read PAGE_SIZE bytes at a go? Any example code is most welcome!

Upvotes: 0

Views: 815

Answers (1)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33076

Don't forget that std::cin is of type std::istream. You can use standard get() on it to retrieve a char at a time with:

char nextVal = std::cin.get();

To read PAGE_SIZE bytes at a go, use read() instead:

char *buffer = new char[PAGE_SIZE];
std::cin.read(buffer, PAGE_SIZE);

Remember to always check error conditions and EOF after reading.

Upvotes: 4

Related Questions