普通实现:
#include <sys/stat.h>//获取文件信息
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <fcntl.h>//open
#include <unistd.h>//read
#include <time.h>
#include<iostream>
using namespace std;
#define N 256
clock_t Start,End;
int getFile_size(const char * path);
int main(int argc, char * argv[]) {
if(argc < 2) {
printf("%s path\n", argv[0]);
return -1;
}
Start = clock();
int cnt = getFile_size(argv[1]);
cout<<"此目录下的文件总大小为"<<cnt<<"KB"<<endl;
End = clock();
cout<<"程序总耗费时间为:" <<((double)(End - Start)/CLOCKS_PER_SEC)<<"ms"<<endl;
return 0;
}
int getFile_size(const char * path) {
int cnt = 0;
DIR * dir = opendir(path);
if(dir == NULL) {
perror("opendir");
exit(0);
}
struct dirent *ptr;
while((ptr = readdir(dir)) != NULL) {
char * dname = ptr->d_name;
if (strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) {
continue;
}
struct stat st;
stat(dname,&st);//获取路径文件信息
if (ptr->d_type == DT_DIR) {
char newpath[N];
sprintf(newpath, "%s/%s", path, dname);
cnt += getFile_size(newpath);//如果是目录的话,递归
}
else if (ptr->d_type == DT_REG) {
cnt += st.st_size;
}
}
closedir(dir);
return cnt;
}
wuliwlll@wuliwlll-virtual-machine:~/Desktop/open$ ./sizeapp /home/wuliwlll/
此目录下的文件总大小为83051KB
程序总耗费时间为:0.027408ms
多线程实现
#include <iostream>
#include <vector>
#include <string>
#include <dirent.h>
#include <sys/stat.h>
#include <pthread.h>
using namespace std;
clock_t Start,End;//计算程序时间
vector<string> files;
pthread_mutex_t mutex;
vector<string> GetDirectoryFile(const string& directory) {
//vector<string> files;
DIR *dir = opendir(directory.c_str());
if (dir == NULL){
return files;
}
struct dirent *ptr;
while ((ptr = readdir(dir)) != NULL) {
string filename = ptr->d_name;
if (filename == "." || filename == "..") continue;//Linux系统默认前两目录为自身.和上级目录..需要过滤
string newpath = directory + "/" + filename;
if (ptr->d_type == DT_DIR) {
GetDirectoryFile(newpath);
} else {
files.push_back(newpath);
}
}
closedir(dir);
return files;
}
int cnt = 0 ;
void* FileSize(void* param) {
while (true) {
pthread_mutex_lock(&mutex);//上锁
if (files.empty()) {
pthread_mutex_unlock(&mutex);
break;
}
string file = files.back();
files.pop_back();
pthread_mutex_unlock(&mutex);//解锁
struct stat st;
stat(file.c_str(), &st);
cnt += st.st_size;
cout << file << ": " << st.st_size <<"KB"<< endl;
}
return NULL;
}
int main(int argc, char *argv[]) {
Start = clock();
if (argc != 2) {
cout << "Usage: " << argv[0] << " directory" << endl;
return 1;
}
string directory = argv[1];
GetDirectoryFile(directory);
pthread_t threads[4];
pthread_mutex_init(&mutex, NULL);//初始化锁
for (int i = 0; i < 4; i++) {
pthread_create(&threads[i], NULL, FileSize, NULL);
}//创建线程 执行回调函数
for (int i = 0; i < 4; i++) {
pthread_join(threads[i], NULL);
}//回收线程
pthread_mutex_destroy(&mutex);//销毁锁
End = clock();
cout<<"程序总耗费时间为:" <<((double)(End - Start)/CLOCKS_PER_SEC)<<"ms"<<endl;
cout<<"此目录下的文件总大小为"<<cnt<<"KB"<<endl;
return 0;
}