193.123.19.116 [Daz] wrote in message news: said:
Is there any way using C library functions to get the size of a directory and its contents (without resorting to using a shell command)?
==================================
Poster's IP address: 193.123.19.116
Posted via
http://nodevice.com
Linux Programmer's Site
Sure! You can calculate the size of each file, then accumulate them!
Quote from busybox:
long du(char *filename)
{
struct stat statbuf;
long sum;
if ((lstat(filename, &statbuf)) != 0) {
perror_msg("%s", filename);
return 0;
}
if (du_depth == 0)
dir_dev = statbuf.st_dev;
else if (one_file_system && dir_dev != statbuf.st_dev)
return 0;
du_depth++;
sum = (statbuf.st_blocks >> 1);
/* Don't add in stuff pointed to by symbolic links */
if (S_ISLNK(statbuf.st_mode)) {
sum = 0L;
if (du_depth == 1) {
}
}
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
char *newfile;
dir = opendir(filename);
if (!dir) {
du_depth--;
return 0;
}
newfile = last_char_is(filename, '/');
if (newfile)
*newfile = '\0';
while ((entry = readdir(dir))) {
char *name = entry->d_name;
if ((strcmp(name, "..") == 0)
|| (strcmp(name, ".") == 0)) {
continue;
}
newfile = concat_path_file(filename, name);
sum += du(newfile);
free(newfile);
}
closedir(dir);
print(sum, filename);
}
else if (statbuf.st_nlink > 1 && !count_hardlinks) {
/* Add files with hard links only once */
if (is_in_ino_dev_hashtable(&statbuf, NULL)) {
sum = 0L;
if (du_depth == 1)
print(sum, filename);
}
else {
add_to_ino_dev_hashtable(&statbuf, NULL);
}
}
du_depth--;
return sum;
}