我必须读取8字节块中的一些二进制文件,然后通过tcp套接字发送这些块。我可以使用C ++迭代器执行此任务吗?喜欢:
FileIterator file("name_file.bin");
for(iter = file.begin(); iter != file.end(); iter++) {
sendTcp(iter);
}
类FileIterator
必须返回将要发送的一些结构。在FileIterator
我的构造函数中,打开二进制文件并读取它。然后创建动态数组并写入文件内容。在每一步迭代器中,我必须从数组中读取下一个块并将其写入struct并返回。
我认为这是一个XY问题。是的,可以使用迭代器来完成,但是迭代器并不是这项工作的最佳选择。为此,使用迭代器是一种有趣的教育体验,但是老了就解决了这个问题,几乎没有什么大惊小怪的,零错误也更容易解决。
#include <iostream>
#include <fstream>
// simple 8 byte struct
struct EightByteStruct
{
uint32_t a;
uint32_t b;
};
// quick hack send routine. Added capacity for some simple error checking.
bool sendTcp(EightByteStruct & test)
{
bool rval = false;
// send test. Set rval true if success
return rval;
}
//main event: read file into struct, write struct to socket
int main()
{
std::ifstream in("filename", std::ios::binary);
EightByteStruct test;
while (in.read((char*)&test, sizeof(test)))
{ // will not enter if sizeof(test) bytes not read from file
if (sendTcp(test))
{
// handle send error
}
}
// test here for any file error conditions you wish to have special handling
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句