Home:ALL Converter>list top 10 files by size in a unix directory

list top 10 files by size in a unix directory

Ask Time:2012-12-27T04:15:09         Author:user1914520

Json Formatter

I am trying a to read a unix directory (including all subdirectories) using c++ and list the top 10 largest files. I have read that I can use #include dirent.h and use struct dirent but I am having trouble passing the directory name as a variable to opendir/readdir. Basically it doesn't recognise it and says file/directory not found. Please can you help me with how I can do this in c++ and print out the top 10 largest files in the directory? Thanks

DIR *dir;
struct dirent *ent;
dir = opendir ("homedir");
if (dir != NULL) {
    while ((ent = readdir (dir)) != NULL) {
        cout << ent->d_name <<endl;
    }

    closedir (dir);
} else {
    cout << "Can't open directory" << endl;
}

Author:user1914520,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14045735/list-top-10-files-by-size-in-a-unix-directory
James Kanze :

You don't really give enough details, but when you are reading\nrecursively, are you postfixing the names you read to the\nprevious names. Reading a directory doesn't change the current\ndirectory, so your function should look more or less like: \n\n\nstd::vector\nreadDirectoriesRecursively( std::string const& path )\n{\n std::vector results;\n for each name in path\n if is directory\n results.insert(\n results.end(),\n readDirectoriesRecursively( path + '/' + filename ) ) ;\n else\n results.push_back( FileInfo( path + '/' + filename ) );\n return results;\n}\n\n\nIn the constructor of FileInfo, use stat to obtain the size. Once you have the results, sort by size, and output the first 10.",
2012-12-26T20:30:03
yy