P
P
Pavel2012-10-02 18:14:04
Qt
Pavel, 2012-10-02 18:14:04

How do I know if there is enough disk space when copying a file?

The task is as follows: the file is copied, if the disk space is over, then stop copying and issue a warning to the user. cross-platform implementation (windows - linux) on Qt is required.

I saw this function on the Internet:

#ifdef _WIN32
    #include <windows.h>
#else // linux stuff
    #include <sys/vfs.h>
    #include <sys/stat.h>
#endif // _WIN32

bool getFreeTotalSpace(const QString& sDirPath,double& fTotal, double& fFree)
{
#ifdef _WIN32

    QString sCurDir = QDir::current().absPath();
    QDir::setCurrent( sDirPath );
    
    ULARGE_INTEGER free,total;
    bool bRes = ::GetDiskFreeSpaceExA( 0 , &free , &total , NULL );
    if ( !bRes ) return false;

    QDir::setCurrent( sCurDir );

    fFree = static_cast<double>( static_cast<__int64>(free.QuadPart) ) / fKB;
    fTotal = static_cast<double>( static_cast<__int64>(total.QuadPart) ) / fKB

#else //linux

    struct stat stst;
    struct statfs stfs;

    if ( ::stat(sDirPath.local8Bit(),&stst) == -1 ) return false;
    if ( ::statfs(sDirPath.local8Bit(),&stfs) == -1 ) return false;

    fFree = stfs.f_bavail * ( stst.st_blksize / fKB);
    fTotal = stfs.f_blocks * ( stst.st_blksize / fKB );

#endif // _WIN32

    return true;
}


but I can't figure it out. tell me how to use it. what exactly is not clear: a boolean value is returned - is this the answer “there is no disk space / there is”? and what is fKB.

thanks in advance

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
agmt, 2012-10-02
@agmt

Why not use posix_fallocate? Well, or more cross QFile:: seek(needSize-1); QFile::write("", 1);

R
rasa, 2012-10-02
@rasa

Boolean - because the function is in C ++, the result is returned in fTotal and in fFree
fKB = 1024

V
vScherba, 2012-10-02
@vScherba

You can also use the standard std::ofstream ofs(filename); ofs.seekp(desired_size); ofs << '\0';
This code, like agmt 's version, backs up a file on disk of the correct size. If there is not enough space, handle the error. If no error occurs, you have guaranteed allocated disk space that no one will take.
In your example, after determining the sufficiency of space, another application can fill up the disk, and you will know about it only during direct writing to the file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question