发送方和接收方的套接字读/写文件大小变化
我想以相同大小的块发送数据。 但如果文件大小不是卡盘大小的倍数,那么将会添加额外的 接收端的尺寸。 我想到的解决方案是获取文件大小并根据文件大小划分块。 但是这个解决方案不起作用任何人都可以告诉我
这是我的代码
total_chunks = size / CHUNK_SIZE;
partial_chunks = size % CHUNK_SIZE;
int write_fd = open("test3.txt",O_CREAT|O_WRONLY,0777);
if(fd != -1)
{
if(total_chunks >= 1)
{
data_chunk = (char *)malloc(sizeof(char) * CHUNK_SIZE);
bzero((char *) data_chunk, sizeof(data_chunk));
for(iteration = 0;iteration <total_chunks;iteration++)
{
read(fd,data_chunk,sizeof(data_chunk));
write(write_fd,data_chunk,CHUNK_SIZE);
}
free(data_chunk);
}
if(partial_chunks != 0)
{
data_chunk = (char *)malloc(sizeof(char) * partial_chunks);
bzero((char *) data_chunk, sizeof(data_chunk));
read(fd,data_chunk,sizeof(data_chunk));
write(write_fd,data_chunk,sizeof(data_chunk));
}
close(fd);
close(write_fd);
}
I want to send the data in same size chunks.
but if file size is not multiple of chuck size then there will be addition of extra
size at receiver side.
I thought of solution get the file size and divide the chunk with respect to file size.
however this solution is not working can anyboby tell me
Here is my code
total_chunks = size / CHUNK_SIZE;
partial_chunks = size % CHUNK_SIZE;
int write_fd = open("test3.txt",O_CREAT|O_WRONLY,0777);
if(fd != -1)
{
if(total_chunks >= 1)
{
data_chunk = (char *)malloc(sizeof(char) * CHUNK_SIZE);
bzero((char *) data_chunk, sizeof(data_chunk));
for(iteration = 0;iteration <total_chunks;iteration++)
{
read(fd,data_chunk,sizeof(data_chunk));
write(write_fd,data_chunk,CHUNK_SIZE);
}
free(data_chunk);
}
if(partial_chunks != 0)
{
data_chunk = (char *)malloc(sizeof(char) * partial_chunks);
bzero((char *) data_chunk, sizeof(data_chunk));
read(fd,data_chunk,sizeof(data_chunk));
write(write_fd,data_chunk,sizeof(data_chunk));
}
close(fd);
close(write_fd);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sizeof(data_chunk) 将为您提供 data_chunk 数据类型的大小,它与 sizeof(char *) 相同。没有函数可以为您提供由 malloc 分配的内存块的大小,只需将其替换为 CHUNK_SIZE 而不是下面的完整块和部分块,即:
sizeof(data_chunk) will give you the size of the datatype of data_chunk, it's the same as sizeof(char *). There is no function that will give you the size of a memory block allocated by malloc, just replace it by CHUNK_SIZE instead for full blocks and partial_chunks further below, i.e: