- #include <stdio.h>
- #include <stdlib.h>
- #include <dirent.h>
- #include <sys/stat.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <unistd.h>
- int count_file_size(const char *dirname);
- unsigned long file_size = 0;
- int main(int argc, char **argv)
- {
- count_file_size(argv[1]);
- printf("%s: %lu", argv[1], file_size);
- return 0;
- }
- int count_file_size(const char *dirname)
- {
- DIR *dp;
- struct dirent *dirp;
- struct stat *buf;
- if ( (dp = opendir(dirname)) == NULL) {
- fprintf(stderr, "Can't open dir %s\\n", dirname);
- exit(1);
- }
- while ( (dirp = readdir(dp) ) != NULL) {
- printf("%s\\n", dirp->d_name);
- #if 1
- if (stat(dirp->d_name, buf) < 0) {
- fprintf(stderr, "Get file stat falied: %s\\n", strerror(errno));
- exit(1);
- }
- if (S_ISDIR(buf->st_mode))
- count_file_size(dirp->d_name);
- else {
- file_size += buf->st_size;
- }
- #endif
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/141120137184.html
来源: http://www.codesnippet.cn/detail/141120137184.html