How can I find the size of all files located inside a folder?

后端 未结 12 2417
萌比男神i
萌比男神i 2020-12-06 05:49

Is there any API in c++ for getting the size of a specified folder?

If not, how can I get the total size of a folder including all subfolders and files?

12条回答
  •  醉话见心
    2020-12-06 06:02

    How about letting OS do it for you:

    long long int getFolderSize(string path) 
    {
        // command to be executed
        std::string cmd("du -sb ");
        cmd.append(path);
        cmd.append(" | cut -f1 2>&1");
    
        // execute above command and get the output
        FILE *stream = popen(cmd.c_str(), "r");
        if (stream) {
            const int max_size = 256;
            char readbuf[max_size];
            if (fgets(readbuf, max_size, stream) != NULL) {
                return atoll(readbuf);
            }   
            pclose(stream);            
        }           
        // return error val
        return -1;
    }
    

提交回复
热议问题