C 套接字:将缓冲区重定向到另一个文件

发布于 2024-10-29 22:43:18 字数 303 浏览 1 评论 0原文

如果之前已经用不同的措辞问过这个问题,我深表歉意。

这是我的问题。我有一个 Linux TCP 服务器客户端关系,在我的代码的某个部分中,服务器会将文件缓冲区的块(比方说 512 字节) write() 到客户端。我希望客户端通过某种方式将缓冲区块向外重定向到已创建的文件(模仿复制效果)来重建另一侧的文件。我正在考虑一个中间人,他会将缓冲区转换为字符,然后使用 fprintf 等将信息推送到文件中(这是我能想到的唯一方法)。然而,这个想法在处理二进制文件时不起作用,因为 ascii 会弄乱二进制文件。

有没有办法将文件缓冲区指针重定向到另一个文件?谢谢!

If this has been asked before in a different wording, I apologize.

Heres my issue. I have a Linux TCP server client relationship and in a certain part of my code, the server will write() chunks (lets say 512 bytes) of a file buffer to the client. I am wanting the client to reconstruct the file on the other side by somehow redirecting the buffer chunks outward to a already made file (mimicking a copy effect). I was considering a middle man whom would translate the buffer into characters and then use fprintf etc. to push the information to a file (this is the only way I can conceive how). However, this idea does not work when working with binary files as ascii would mess up the binary.

Is there a way to redirect a file buffer pointer into another file? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

新人笑 2024-11-05 22:43:18

使用recv从套接字读取缓冲区,并使用fwrite将其写入文件。当您打开本地文件时,请务必使用“wb”作为模式。

编辑:这是总体思路的草图:

socket input = open_socket(server, server_port);   
FILE *file = fopen("localfile.bin", "wb");
char buffer[some_size];

do { 
    size_t received = recv(input, some_size);
    fwrite(buffer, received, 1, file);
} while (received != 0);

Read a buffer from the socket using recv, and write it to the file using fwrite. When you open the local file, before sure to use "wb" as the mode.

Edit: Here's a sketch of the general idea:

socket input = open_socket(server, server_port);   
FILE *file = fopen("localfile.bin", "wb");
char buffer[some_size];

do { 
    size_t received = recv(input, some_size);
    fwrite(buffer, received, 1, file);
} while (received != 0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文