简体   繁体   中英

Storing the output of read() from a socket in a char variable

What's the easiest way of storing the output from a read() or recv() operation from a Socket in a char variable?

I'm passing a piece of text from client to server and need to read it into a char variable which will then be displayed and used further down the application.

如果您正在从套接字读取数据,则只需将char缓冲区的地址作为第二个参数传递给read() (或者,如果您使用其中任何一个,则将recv()recvfrom()的第二个参数传递)。

You can try something like this:

char buf[1024];
ssize_t n = read(fd, buf, sizeof(buf));

Don't forget to check and interpret the return value n .

If you want to pass the data around, you can also use a vector :

std::vector<char> buf(1024);
ssize_t n = read(fd, buf.data(), buf.size());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM