c++ - c socket多次调用read

标签 c++ c sockets tcp

我正在写 3200 个 float ,如下所示:

float fft[3200] = {0};
get_fft_frame(dev, fft, 3200); // rf sensor
int written = write(sd, fft, sizeof(fft));

然后像这样阅读:

float *fft = new float[3200];
int inRead = 0;
while (inRead < (3200*4)) {
    //sleep(1);
    int bytesRead = read(sd, fft + inRead, (3200*4) - inRead);
    inRead += bytesRead;
}

所有数据都在 1 次写入中写入,但需要两次读取调用才能获取所有数据。第一次读取返回 11584,第二次返回 1216。

问题是第二个读取调用只读取零。但是,如果我取消注释 sleep 调用,它会读取所有正确的数据。

有没有更好的方法来不 sleep 地获取数据?

最佳答案

你混淆了你的偏移量。 inRead 以字节为单位,但当您将其添加到 fft 时,它会根据指针算术规则乘以 sizeof floatread() 调用中的偏移表达式应该是

((char*)fft)+inRead

关于c++ - c socket多次调用read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757853/

相关文章:

c++ - 降低 C++ 中的圈复杂度

c++ - rand() 介于 0 和 1 之间

c++ - 当 const 引用绑定(bind)到临时引用时,堆栈中会发生什么?

c - 使用 MPI 在后台收听和回复

string - 音频文件可以包含换行符吗?

c++ - 如何正确声明模板类的嵌套类的友元?

c - c 语句中的乘法在单步完成和多步完成时会给出不同的结果吗?

c - C中输入十进制数

c - 从 sockaddr_storage 中提取 IP 地址和端口信息

c - TCP/IP 套接字 API 书籍