In: Computer Science
c program
//the file's size in bytes
unsigned int fileSize(const char* name){
return 0;
}
//same as fileSize except if the file is a directory then it
recursively finds the size of directory and all files it
contains
unsigned int fileSizeRec(const char* name){
return 0;
}
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
//the file's size in bytes
unsigned int fileSize(const char* name){
struct stat st;
stat(name, &st);
return st.st_size;
}
//same as fileSize except if the file is a directory then it recursively finds the size of directory and all files it contains
unsigned int fileSizeRec(const char* name){
struct stat st;
stat(name, &st);
// check if this is a file
if(S_ISREG(st.st_mode)) {
return fileSize(name);
} else {
// to calculate total size of the current directory
unsigned int directory_size = 0;
// Open current directory
DIR *pDir;
if ((pDir = opendir(name)) != NULL) {
struct dirent *pDirent;
// read directory's content one by one.
while ((pDirent = readdir(pDir)) != NULL){
// create the relative path to the file inside folders
char buffer[PATH_MAX + 1];
strcat(strcat(strcpy(buffer, name), "/"), pDirent->d_name);
// If current entry in directory, is another directory
// and it is not . or .. (which is for parent and current
// directory) pointers..
if (pDirent->d_type == DT_DIR) {
if (strcmp(pDirent->d_name, ".") != 0 && strcmp(pDirent->d_name, "..") != 0) {
// recursively find the size of internal directory
directory_size += fileSizeRec(buffer);
}
} else {
// current entry is a file, add its size
directory_size += fileSize(buffer);
}
}
closedir(pDir);
}
return directory_size;
}
}
int main(void) {
int x = fileSizeRec("..");
printf("%d", x);
return 0;
}