I am supposed to go through each file or directory for a given directory, but I can't get it to work calculate the sum of bytes occupied for every file in the directory.
Here is the code that I've written so far. (Also I'm not sure how to let the user type in the directory; I tried cin
or getline
but it didn't work.)
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
using namespace std;
int main (void)
{
int reg = 0;
int der = 0;
size_t size = 0;
DIR * dirp;
struct dirent *entry;
struct stat file_stats;
dirp = opendir("/usr/share/");
while ((entry = readdir(dirp)) != NULL) {
if (entry->d_type == DT_REG)
{
reg++;
stat(entry->d_name, &file_stats);
size += (unsigned int) file_stats.st_size;
}
else if (entry->d_type == DT_DIR)
{
der++;
}
}
closedir(dirp);
printf("The total number of directories in directory is %d \n", reg);
printf("The total number of files in directory is %d \n", der);
printf("The total number of bytes occupied by all files in directory is %zu\n", size);
return 0;
}
When I run it from the /usr/share/
it always returns 0, but it works when I change the directory to the current directory.