说明:
本代码的作用是:
1.获取指定目录前缀下的当前工作目录所有目录;
2.遍历获取的所有目录,获得目录下的指定后缀名的所有文件名;
3.以dir1/file1.abc, dir1/file2.abc, dir2/fff.abc, dir2/fff.abc…为例, 以目录为单位两两取出调用可执行程度compare进行比对, 并将执行结果使用popen返回;
4.将结果保存到指定文件中去
#include <iostream>
#include <fstream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <dirent.h>
#include <algorithm>
using namespace std;
/*
* 获取指定目录下,带有指定前缀的文件夹名称列表
*/
vector<string> get_sub_dirs(string path, string prefix = "")
{
vector<string> ret;
DIR *dir;
struct dirent *ptr;
if( (dir = opendir(path.c_str())) == NULL ) {
cerr << "open dir fail" << endl;
exit(-1);
}
while((ptr = readdir(dir)) != NULL) {
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
continue;
}
if(4 == ptr->d_type) {
string tmp(ptr->d_name);
if(tmp.find(prefix) == 0) {
ret.push_back(path + "/" + ptr->d_name);
//cout << ptr->d_name << endl;
}
}
}
closedir(dir);
sort(ret.begin(), ret.end());
return ret;
}
/*
* 获取指定目录下指定后缀名的所有文件列表
*/
vector<string> get_need_files(string path)
{
vector<string> ret;
DIR *dir;
struct dirent *ptr;
if( (dir = opendir(path.c_str())) == NULL ) {
cerr << "open dir fail" << endl;
exit(-1);
}
while((ptr = readdir(dir)) != NULL) {
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
continue;
}
if(8 == ptr->d_type) {
string tmp = ptr->d_name;
int pos = (tmp).find_last_of('.');
if(pos == -1) {
continue;
}
string suffix = tmp.substr(pos + 1);
//cout << suffix << endl;
if(suffix == "abc") {
ret.push_back(ptr->d_name);
cout << ptr->d_name << endl;
}
}
}
closedir(dir);
return ret;
}
int main(int argc, char **argv)
{
if(argc < 3) {
cout << "dir prefix is inneed." << endl;
cout << "usage: ./main dir_prefix outPath!!!";
return -1;
}
string prefix = argv[1];
string outPath = argv[2];
char pwd_path[256];
if( !getcwd(pwd_path, 256) )
{
cerr << "get cureent path fail" << endl;
return -1;
}
string curPath = pwd_path;
cout << curPath << endl;
vector<string> sub_dirs = get_sub_dirs(curPath, prefix);
ofstream out;
out.open(outPath.c_str());
char buff[1024];
//调用比对程度,并通过popen读取比对结果,将结果保存到指定输出文件中
for(int i = 0; i < sub_dirs.size(); ++ i) {
for(int j = i + 1; j < sub_dirs.size(); ++ j) {
vector<string> file_list1 = get_need_files(sub_dirs[i]);
vector<string> file_list2 = get_need_files(sub_dirs[j]);
for(vector<string>::iterator it = file_list1.begin(); it != file_list1.end(); ++ it) {
for(vector<string>::iterator pp = file_list2.begin(); pp != file_list2.end(); ++ pp) {
memset(buff, 0, sizeof(buff));
FILE *stream;
string cmd = "./compare " + sub_dirs[i] + "/" + *it
+ " " + sub_dirs[j] + "/" + *pp;
stream = popen(cmd.c_str(), "r");
fread(buff, sizeof(char), sizeof(buff), stream);
out << cmd << endl;
out << buff;
}
}
}
}
out.close();
return 0;
}