Finding size of a directory

Finding size of a directory using recursion


C++ : Finding size of a directory using recursion. Implemented in C++14

#include<iostream>
#include<vector>
#include<list>
#include<map>

using namespace std;

class File {

    public:
    char type;
    string name;
    int size;

    File(char arg_type, string arg_name, int arg_size) : type(arg_type), name(arg_name), size(arg_size)
    { }
    // Instead of writing a Compare class wth operator() overloaded,
    // we can overload < operator in the File class as below
    /*
    bool operator< (const File & f) const {
        if (f.name < this->name)
            return true;
    }*/
};

class CompareFileName {

    public:
    bool operator() (const File & a, const File & b) const {
        return (a.name < b.name);
    }
};

class FileSystem {

    private:
    map<File, vector<File>, CompareFileName> fs;

    public:

    FileSystem(map<File, vector<File>, CompareFileName> arg_fs) : fs(arg_fs)
    {}

    int FindDirSize(File dir) {
        int sz = 0;
        for (const auto& fileobj : fs[dir]) {
            if (fileobj.type == 'D') {
                sz += FindDirSize(fileobj);
            } else {
                sz += fileobj.size;
            }
        }
        return sz;
    }
};

int main(){

    map<File, vector<File>, CompareFileName> fs;

    File root('D', "Root", 0);

    File d1('D', "D1", 0);
    File f1('F', "F1", 1);
    File f2('F', "F2", 2);
    File f3('F', "F3", 3);

    File d2('D', "D2", 0);
    File f4('F', "F4", 4);
    File f5('F', "F5", 5);
    File f6('F', "F6", 6);

    File d3('D', "D3", 0);
    File f7('F', "F7", 7);
    File f8('F', "F8", 8);
    File f9('F', "F9", 9);

    vector<File> inside_d1 = { f1, f2, f3 };
    fs.insert({d1, inside_d1});

    vector<File> inside_d2 = { f4, f5, f6 };
    fs.insert({d2, inside_d2});

    vector<File> inside_d3 = { f7, f8, f9 };
    fs.insert({d3, inside_d3});

    vector<File> inside_root = { d1, d2, d3 };
    fs.insert({root, inside_root});

    FileSystem fsobj(fs);
    cout << "Size of root directory : " << fsobj.FindDirSize(root) << endl;
    cout << "Size of d1 directory : " << fsobj.FindDirSize(d1) << endl;
    cout << "Size of d2 directory : " << fsobj.FindDirSize(d2) << endl;
    cout << "Size of d3 directory : " << fsobj.FindDirSize(d3) << endl;
    return 0;
}

Output of finding the size of a directory using recursion. Implemented in C++14.

Size of root directory : 45
Size of d1 directory : 6
Size of d2 directory : 15
Size of d3 directory : 24

Copyright © 2020, Algotree.org.
All rights reserved.