Check if there is enough free disk space to save the file; reserve it

I am writing a C ++ program that will print large (2-4 GB) files.

I would like to make sure that there is enough disk space to store the files before I start writing them. If possible, I would like to reserve this place.

This happens on a Linux based system.

Any thoughts on a good way to do this?

+4
source share
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 a file. As far as I know, there is no standard way to get a file descriptor ( fd ) from std::fstream .

Given this, I would pre-allocate disk space as a separate step in this process. It would be:

This can be turned into a short function that needs to be called before you open fstream .

+7
source

Use the aix response ( posix_fallocate() ), but since you are using C ++ streams, you will need to hack a bit to get the stream file descriptor.

To do this, use the code here: http://www.ginac.de/~kreckel/fileno/ .

+1
source

Source: https://habr.com/ru/post/1398890/


All Articles