简体   繁体   English

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

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

I'm writing a C++ program which will be printing out large (2-4GB) files.我正在编写一个 C++ 程序,它将打印出大型(2-4GB)文件。

I'd like to make sure that there's sufficient space on the drive to save the files before I start writing them.开始写入文件之前,我想确保驱动器上有足够的空间来保存文件。 If possible, I'd like to reserve this space.如果可能,我想保留这个空间。

This is taking place on a Linux-based system.这是在基于 Linux 的系统上进行的。

Any thoughts on a good way to do this?关于做到这一点的好方法的任何想法?

Take a look at posix_fallocate() :看看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.

edit In the comments you indicate that you use C++ streams to write to the file.编辑在注释中,您指出您使用 C++ 流写入文件。 As far as I know, there's no standard way to get the file descriptor ( fd ) from a std::fstream .据我所知,没有从std::fstream获取文件描述符( fd )的std::fstream

With this in mind, I would make disk space pre-allocation a separate step in the process.考虑到这一点,我会将磁盘空间预分配作为该过程中的一个单独步骤。 It would:它会:

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

This can be turned into a short function to be called before you even open the fstream .这可以变成一个简短的函数,在您打开fstream之前就可以调用它。

If you are using C++ 17 , you should do it with std::filesystem::resize_file如果您使用的是C++ 17 ,则应该使用std::filesystem::resize_file

As shown in this post这篇文章所示

Use aix's answer ( posix_fallocate() ), but since you're using C++ streams, you'll need a bit of a hack to get the stream's file descriptor.使用 aix 的答案 ( posix_fallocate() ),但由于您使用的是 C++ 流,因此您需要一些技巧来获取流的文件描述符。

For that, use the code here: http://www.ginac.de/~kreckel/fileno/ .为此,请使用此处的代码: http : //www.ginac.de/~kreckel/fileno/

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

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