使用mmap增加文件的大小 [英] Increasing a file's size using mmap

查看:458
本文介绍了使用mmap增加文件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上的Python中,我可以通过以下方式创建大文件

In Python on Windows I can create a large file by

    from mmap import mmap
    f = open('big.file', 'w')
    f.close()
    f = open('big.file', 'r+')
    m = mmap(f.fileno(), 10**9)

现在big.file大约是1 GB.但是,在Linux上,这将返回ValueError: mmap length is greater than file size.

And now big.file is (about) 1 gigabyte. On Linux, though, this will return ValueError: mmap length is greater than file size.

有没有办法在Linux上获得与Windows相同的行为?也就是说,要使用mmap来增加文件的大小?

Is there a way to get the same behavior on Linux as with Windows? That is, to be able to increase a file's size using mmap?

推荐答案

至少在POSIX系统上,mmap()不能用于增加(或减小)文件的大小. mmap()的功能是对文件的一部分进行内存映射.合乎逻辑的是,您要求映射的东西应该确实存在!坦白说,我真的很惊讶您实际上能够在MS Windows下执行此操作.

On POSIX systems at least, mmap() cannot be used to increase (or decrease) the size of a file. mmap()'s function is to memory map a portion of a file. It's logical that the thing you request to map should actually exist! Frankly, I'm really surprised that you would actually be able to do this under MS Windows.

如果要扩展文件,请先ftruncate(),然后再mmap().

If you want to grow a file, just ftruncate() it before you mmap() it.

这篇关于使用mmap增加文件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆