不知道可以grep -r,然后又有需求,又不会shell,只能翻着apue自己用c/c++写了一个。后来man grep了一下,赫然发现grep -r,还比我这个程序快。。。哎,输出懒得优化格式了。 #include<iostream> #include<string> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<stdlib.h> using std::string; using std::cout; using std::endl; void recurgrep(const string& str,const string& path) { string cmd = "grep /""+str+"/""; struct stat statbuf; struct dirent* dirp = NULL; DIR *pDir; pDir = opendir(path.c_str()); if(pDir == NULL) return; while(NULL != (dirp=readdir(pDir))) { if(strcmp(dirp->d_name,".") == 0||strcmp(dirp->d_name,"..")==0) continue; string curpath = path+"/"+dirp->d_name; if(lstat(curpath.c_str(),&statbuf)<0) continue; if(S_ISDIR(statbuf.st_mode) == 0) { string cmd_tmp = cmd+" "+curpath; cout<<"File:"<<curpath<<endl; system(cmd_tmp.c_str()); cout<<endl; } else { recurgrep(str,curpath); } } } int main(int argc,char* argv[]) { if(argc != 3) { cout<<"Usage:recurgrep /"search_str/" /"search_path/"!"<<endl; return 1; } string search_str = argv[1]; string search_path = argv[2]; recurgrep(search_str,search_path); return 0; }