【发布时间】:2012-02-28 19:54:30
【问题描述】:
我正在编写一个 C++ 程序,它将打印出大 (2-4GB) 文件。
我想确保驱动器上有足够的空间来保存文件在我开始编写文件之前。如果可能的话,我想保留这个空间。
这是在基于 Linux 的系统上进行的。
有什么好的方法可以做到这一点吗?
【问题讨论】:
我正在编写一个 C++ 程序,它将打印出大 (2-4GB) 文件。
我想确保驱动器上有足够的空间来保存文件在我开始编写文件之前。如果可能的话,我想保留这个空间。
这是在基于 Linux 的系统上进行的。
有什么好的方法可以做到这一点吗?
【问题讨论】:
NAME
posix_fallocate - allocate file space
SYNOPSIS
int posix_fallocate(int fd, off_t offset, off_t len);
DESCRIPTION
The function posix_fallocate() ensures that disk space is allocated for
the file referred to by the descriptor fd for the bytes in the range
starting at offset and continuing for len bytes. After a successful
call to posix_fallocate(), subsequent writes to bytes in the specified
range are guaranteed not to fail because of lack of disk space.
edit 在 cmets 中,您表明您使用 C++ 流写入文件。据我所知,没有从std::fstream 获取文件描述符(fd)的标准方法。
考虑到这一点,我会将磁盘空间预分配作为流程中的一个单独步骤。它会:
open()文件;posix_fallocate();close() 文件。这可以变成一个短函数,在你打开fstream之前调用。
【讨论】:
ostream 中取出fd,但是AFAIK 没有标准的方法可以做到这一点。我个人只会open() 文件,使用posix_fallocate() 和close() 它。然后你可以使用 C++ I/O 重新打开它,写入内容等。
read() 和 write() 调用。但重新开放可能更容易。
ios::in | ios::out指定为ofstream构造函数的第二个参数,文件不会被截断。
使用 aix 的答案 (posix_fallocate()),但由于您使用的是 C++ 流,因此需要一些技巧来获取流的文件描述符。
为此,请在此处使用代码:http://www.ginac.de/~kreckel/fileno/。
【讨论】:
如果您使用的是 C++ 17,则应使用 std::filesystem::resize_file
【讨论】: