繁体   English   中英

检查是否有足够的磁盘空间来保存文件; 保留它

[英]Check if there is sufficient disk space to save a file; reserve it

我正在编写一个 C++ 程序,它将打印出大型(2-4GB)文件。

开始写入文件之前,我想确保驱动器上有足够的空间来保存文件。 如果可能,我想保留这个空间。

这是在基于 Linux 的系统上进行的。

关于做到这一点的好方法的任何想法?

看看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 )的std::fstream

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

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

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

如果您使用的是C++ 17 ,则应该使用std::filesystem::resize_file

这篇文章所示

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM