Programmer's Guide to the WvStreams Libraries | ||
---|---|---|
Prev | Chapter 10. WvStream - communications fundamentals | Next |
Here's a sample program that uses the read() and write() member functions. Usually, these functions are used more often than getline() because WvStreams are commonly used to manipulate binary data rather than line-by-line data.
/* * A WvStream example. * * Some text about this example... */ #include <wvstream.h> int main() { char buffer[10]; size_t numread; while (wvcon->isok()) { numread = wvcon->read(buffer, sizeof(buffer)); if (numread) { wvcon->print("You said: "); wvcon->write(buffer, numread); wvcon->print(" (%s bytes)\n", numread); } } }
Unlike getline(), read() isn't very smart. You must supply it with a buffer and tell it how large the buffer is. However, there's no guarantee that read() will fill the entire buffer or any of it -- you should _always_ check the return value (numread, in this case) to find out how many bytes were read. You'll find out later (when we talk about select()) that this is actually the right thing to do -- the last thing you want in most WvStreams programs is for read() to sit doing nothing until a buffer fills up.
On the other hand, the write() function has a built-in buffer, so as long as the stream is alive, the return value of write() should always be the same as the length you provide as the second parameter.
The print() function works sort of like printf(). It uses the complex constructor for WvString to type-safely format strings, and then the write() function to send them out to the stream.