截断内存映射文件
我想使用读/写内存映射文件来管理我正在创建的一些索引(unsigned int
)。
我最初不知道文件的大小,所以我打算制作它关于从 4K 开始,并相应发展。
但是,我不确定在完成地图后如何截断文件。因此,如果我在文件中只使用大约 1K,我想将其截断为 1K,而不是在此过程中浪费 3K。我关心的并不是特别浪费文件空间,而是我检查文件的大小以确定我有多少个 unsigned int
。
编辑
所以为了澄清...当文件是内存映射时...我正在分配 4K 块...当我完成内存映射文件时,我想清理该文件,以便这正是我所投入的。
I would like to use a read/write memory mapped file to manage some indexes (unsigned int
) I'm creating.
I've followed the code examples found here and here
I don't know the size of the file initially, so I plan on making it about 4K to start with and grow accordingly.
However, I'm unsure how to truncate the file once I'm done with the map. So if I only use about 1K in the file, I would like to truncate it to 1K and not waste 3K in the process. My concern is not specifically with wasting file space, but rather I check the size of the file to determine how many unsigned int
I have.
EDIT
So to clarify...while the file is memory mapped...I'm allocating 4K chunks...when I'm done with the memory mapped file, I want to cleanup the file so it is exactly what I've put into it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 ftruncate 截断文件,它只需要文件描述符和大小。然后,稍后您可以使用
fstat
查询基础文件的属性,并使用从中获取的大小来确定未来映射的尺寸。Use
ftruncate
to truncate your file, it just requires the file descriptor and a size. Then later you can usefstat
to query the properties of the underlying file and use the size you obtain from there to dimension future mappings.如果您 ftruncate() 文件,则必须“同时” mremap() 将映射映射到新大小。您可以对范围执行类似的操作(但这可能会导致 mremap 将段放置在地址空间的不同部分)
If you ftruncate() the file, you'll have to "simultaneously" mremap() the mapping to the new size. You can do a similar thing for extents (but that may cause mremap to place the segment in a different part of your address space)
当您尝试优化时,请使用 getpagesize() 返回的值。那是标准的系统内存页面大小,不需要截断它。
When you try to optimize, use the value that getpagesize() returns. That is the standard system memory page size, no need to truncate it.