2012-02-28 85 views
4

我正在写一个C++程序,它将打印出大(2-4GB)的文件。检查是否有足够的磁盘空间来保存文件;保留它

我想确保驱动器上有足够的空间来保存之前我开始编写它们。如果可能的话,我想预留这个空间。

这发生在基于Linux的系统上。

有没有想过要做到这一点的好方法?

回答

7

posix_fallocate()看看:

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. 

编辑在表明您使用C++流写入到文件中的注释。据我所知,没有从std::fstream获取文件描述符(fd)的标准方法。

考虑到这一点,我会在磁盘空间预先分配过程中的一个单独的步骤。它会:

  1. open()该文件;
  2. 使用posix_fallocate();
  3. close()该文件。

在打开fstream之前,这可以变成一个简短的函数。

+2

这看起来像一个C风格的函数。关于如何将它与C++流操作符混合的想法? – Richard 2012-02-28 20:00:12

+1

@Richard:你可以尝试从'ostream'中取出'fd',但AFAIK没有标准的方法来做到这一点。我个人只会'打开()'文件,使用'posix_fallocate()'和'close()'它。然后,您可以使用C++ I/O重新打开它,写入内容等。 – NPE 2012-02-29 07:58:50

+0

如果需要,您也可以编写自己的streambuf以包装低级别的read()和write()调用当然,没有人会替换你下面的文件。但重新开放可能更容易。 – bdonlan 2012-02-29 08:21:41

1

使用aix的答案(posix_fallocate()),但由于您使用的是C++流,因此您需要一些手段来获取流的文件描述符。

为此,请使用此处的代码:http://www.ginac.de/~kreckel/fileno/

相关问题