在 Erlang 中写入随机访问文件

发布于 2024-09-29 20:18:12 字数 211 浏览 2 评论 0原文

收到一定量的数据后如何写入文件?

我知道可以打开该文件,然后可以使用 file:pwrite(Position, Bin) 对其进行写入。

我想知道的是数据是否正在下载并且需要写入文件。如何有效地做到这一点?例如使用缓冲区(如何写入缓冲区?)

另外,文件是否在下载完成之前一直保持打开状态,或者每次到达缓冲区并且需要写入数据时都打开文件?

谢谢

How does one write to a file after a certain amount of data is received?

I know the file can be opened and then it can be written to using file:pwrite(Position, Bin).

The thing I would like to know is if data is e.g. being downloaded and needs to be written to the file. How does one do this efficiently? e.g. using a buffer(how is a buffer written?)

Also Is the file kept open the entire time until the download is done or is it opened each time the buffer is reached and the data needs to be written?

Thanks

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

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

发布评论

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

评论(3

不必了 2024-10-06 20:18:12

如果您希望 erlang 为您处理缓冲文件写入,您可以使用 {delayed_write, Size, Delay} 选项打开文件。然后,您可以根据需要进行 io:write 操作,当缓冲区达到 Size 字节时,虚拟机将负责将这些请求批量处理到一个操作系统写入调用中,或自缓冲区开始填充后的 Delay 毫秒后。

这种方法允许您在每次从网络接收数据时发出 io:write 调用,但知道您不会为每个字节发出系统调用(如果您确实出现了病态的网络行为)。

If you'd like erlang to take care of buffering file writes for you, you can open a file with the {delayed_write, Size, Delay} option. Then you can just io:write to it as much as you like and the VM will take care of batching those requests into one OS write call when the buffer reaches Size bytes, or after Delay milliseconds since the buffer started to fill.

This approach would allow you to issue io:write calls every time you receive data from the network but know that you won't be issuing system calls for every byte (if you got really pathological network behaviour).

夏花。依旧 2024-10-06 20:18:12

最有效的方法是将数据附加到内存缓冲区(IO 列表?),并在一次操作中将其写入文件。如果您希望打开文件并写入每个数据块,当数据块到达时,您可以以追加模式打开文件:

> file:write_file(FileName, DataToWrite, [append]).

每次写入都会将数据追加到文件末尾。

The most efficient method is to append the data to an in-memory buffer (an IO list?) and write it to a file in one operation. If you wish to open the file and write each block of data, as it arrives, you can open the file in appendmode:

> file:write_file(FileName, DataToWrite, [append]).

Each write will append the data to the end of the file.

余生共白头 2024-10-06 20:18:12

我认为 file:pwrite/3 有你需要什么。

I think file:pwrite/3 has what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文