gpt4 book ai didi

套接字的描述符可以转换为文件指针吗?

转载 作者:可可西里 更新时间:2023-11-01 02:31:17 25 4
gpt4 key购买 nike

我通过以下方式获得了 TCP 套接字的描述符:

int desc = accept(socket_descriptor, &client_address, &len)

现在从这个描述符 desc 我想得到一个文件指针。 fdopen() 可以在这里使用吗?

我想要获取文件指针的原因是因为我正在更改将数据写入本地文件的现有代码。现在,我想扩展它的功能,以便它可以选择性地写入 TCP 客户端。我不想重写所有功能,而是想以某种方式使用现有的基础设施。现有函数使用文件指针写入文件。我想知道是否可以在不做任何更改的情况下将相同的函数写入 TCP 流。

最佳答案

是的,fdopen()正是您所需要的。这是man page是这样说的:

The fdopen() function associates a stream with the existing file descriptor, fd. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fd, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed. The result of applying fdopen() to a shared memory object is undefined.

但在应用于套接字描述符时要谨慎使用。高级 I/O 函数使用缓冲,并且可能以不同方式发送数据(即,只要在流中找到 \n 就刷新,插入 \r)等。

关于套接字的描述符可以转换为文件指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com