Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

linux

file-io

I'm writing a C++ program which will be printing out large (2-4GB) files.

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.

Any thoughts on a good way to do this?

like image 243
Richard Avatar asked Jan 17 '23 08:01

Richard


2 Answers

Take a look at 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. As far as I know, there's no standard way to get the file descriptor (fd) from a 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;
  2. use posix_fallocate();
  3. close() the file.

This can be turned into a short function to be called before you even open the fstream.

like image 143
NPE Avatar answered Feb 01 '23 11:02

NPE


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.

For that, use the code here: http://www.ginac.de/~kreckel/fileno/.

like image 28
Clark Gaebel Avatar answered Feb 01 '23 12:02

Clark Gaebel