在 Erlang 中写入随机访问文件
收到一定量的数据后如何写入文件?
我知道可以打开该文件,然后可以使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望 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 justio: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 reachesSize
bytes, or afterDelay
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).最有效的方法是将数据附加到内存缓冲区(IO 列表?),并在一次操作中将其写入文件。如果您希望打开文件并写入每个数据块,当数据块到达时,您可以以追加模式打开文件:
每次写入都会将数据追加到文件末尾。
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
append
mode:Each write will append the data to the end of the file.
我认为
file:pwrite/3
有你需要什么。I think
file:pwrite/3
has what you need.