Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am able to output file directory. I would like to ad file size to the output as well.

What I have tried:

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

/*function... might want it in some class?*/
int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);

    return 0;
}

int main()

{std::ofstream outputFile;
outputFile.open("Files.txt");
    string dir = string(".");
    vector<string> files = vector<string>();

    getdir(dir,files);

    for (unsigned int i = 0;i < files.size();i++) {
        outputFile << files[i] << endl;


    }

    return 0;
}
Posted
Updated 27-Apr-18 22:01pm

1 solution

Create a FileItem class that will contain the name and the size in bytes. As you read each directory entry you need to create a new FileItem object. Add in the name and then test if it is a file or a directory. If it is a file then get its size and add that to the object. You can then build a vector of your objects (or pointers to them) which your main method can use to write to the output file, or display on screen.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900