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

Ric*_*ard 4 c++ linux file-io

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

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

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

有什么好想法吗?

NPE*_*NPE 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.
Run Code Online (Sandbox Code Playgroud)

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

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

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

这可以变成一个简短的函数,在你打开之前调用fstream.

  • 这看起来像C风格的功能.关于如何将它与C++流操作符混合的想法? (2认同)