-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirsize.c
More file actions
executable file
·77 lines (69 loc) · 1.79 KB
/
dirsize.c
File metadata and controls
executable file
·77 lines (69 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
long totalbytes = 0;
long dirsize(const char* directory, int verbose)
{
struct dirent *de;
struct stat s;
char pathname[PATH_MAX];
DIR * dir;
//long total_items = 0;
long filesize = 0;
dir = opendir(directory);
if (dir == NULL)
{
printf("Failed to open %s.\n", directory);
return -1;
}
while ((de = readdir (dir)) != NULL)
{
if (de->d_type == DT_REG)
{
filesize = 0; //be sure to reset this each time to avoid inaccuracy
sprintf(pathname, "%s/%s", directory, de->d_name);
if (stat(pathname, &s))
{
printf("Error in stat!\n");
return -1;
}
if (verbose)
{
printf("%s/%s : %ld bytes (%f MB)\n", directory, de->d_name, s.st_size, (float) s.st_size / 1024 / 1024);
}
filesize = s.st_size; //put file size into filesize variable
totalbytes += filesize; //increment totalbytes
}
if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
{
sprintf(pathname, "%s/%s", directory, de->d_name);
dirsize(pathname, verbose); //recursion: keep looping until no more subdirs remain
}
}
closedir(dir);
return totalbytes;
}
long compute_size(const char* directory, int verbose)
{
long space = dirsize(directory, verbose);
return space;
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("Usage: dirsize DIRECTORY\n");
return -1;
}
int verbose = 0; //show or hide individual computations
long space = compute_size(argv[1], verbose);
if (space != -1)
{
float space_mb = (float) space / 1024 / 1024;
printf("space occupied: %ld bytes\n", space);
printf("(%f MB)\n", space_mb);
}
return 0;
}