如何在C ++中的char数组中逐行读取二进制文件? 像这样:
struct packet
{
unsigned int ack;
char data[994];
int sequence_number;
unsigned long checksum;
int lenghtFile;
}dummy;
fstream file1;
file1.open("filename.txt",ios::binary);
if(!file1)
{
cout<<"\n error opening file \n";
}
else
{
while(1)
{
if(file1.eof()!=0)
{break;}
else
{//
file1.read(dummy.data,994);
sendto(connfd,(struct packet*)&dummy,sizeof(struct packet),0,
(sockaddr*)&server,sizeof(server));
}
}
}
答案 0 :(得分:0)
这:
while(1)
{
if(file1.eof()!=0)
{break;}
else
{//
file1.read(dummy.data,994);
sendto(connfd,(struct packet*)&dummy,sizeof(struct packet),0,(sockaddr *)&server,sizeof(server));
}
......看起来它基本上是一种模仿while (!file1.eof())
的冗长方式,许多答案都是基本上保证的问题。我可能会把它写成:
while (file1.read(...))
sendto(...);
但是,我认为,我会更进一步,至少operator>>
(以及可能operator>>
)重载packet
类型:
struct packet {
// ...
friend std::istream &operator>>(std::istream &is, packet &p) {
return is.read(p.data, sizeof(p.data));
}
// and possibly:
friend UDP_iterator operator<<(udp_iterator &c, packet &p) {
return sendto(c.fd, &p, sizeof(p), 0, c.server, sizeof(c.server));
}
};
...其中udp_iterator
类似于ostream_iterator
,但会写入套接字而不是流。请注意,周围有许多类似的类。大多数提供连接到TCP套接字的流缓冲类,但UDP套接字不应该增加任何困难。
如果正确重载,您应该可以使用以下内容将文件中的数据复制到套接字:
std::copy(std::istream_iterator<packet>(file1),
std::istream_iterator<packet>(),
UDP_iterator<packet>(server));