Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <boost/filesystem.hpp>
- #include <boost/range/iterator_range.hpp>
- #include <string>
- #include <vector>
- #include <fstream>
- #include <sstream>
- #include <boost/algorithm/string/predicate.hpp>
- using namespace boost::filesystem;
- using namespace std;
- //determines whether a file is a .txt file or not
- bool isTxtFile(string a){
- string tmp = "";
- int length = a.length();
- if(length < 4){
- return false;
- }else {
- for (int j = length-4; j < length; j++){
- tmp += a[j];
- }
- return (tmp == ".txt");
- }
- }
- //returns a string vector containing all .txt files in current directory
- vector<string> filesToSearch(){
- vector<string> file_names;
- path p(".");
- for (directory_iterator itr(p); itr!=directory_iterator(); ++itr)
- {
- if (isTxtFile(itr->path().filename().string())){
- file_names.push_back(itr->path().filename().string());
- }
- }
- return file_names;
- }
- void searchFiles(vector<string> searchFiles, string keyword){
- int line_count = 0;
- int word_count = 0;
- int file_count = searchFiles.size();
- bool word_found = false;
- for (int i = 0; i < file_count; i++){
- string line_string;
- ifstream f(searchFiles[i]);
- if (f.is_open()){
- while (!f.eof()){
- getline(f, line_string), line_count++;
- istringstream isis(line_string);
- string tmp_word;
- while (isis >> tmp_word){
- if (boost::iequals(tmp_word, keyword)){
- if (!word_found){
- cout << keyword << ":" << endl;
- word_found = true;
- }
- word_count++;
- }isis.clear();
- }
- if (word_count == 1){
- cout << "\tFound in \"" << searchFiles[i] << "\" at line " << line_count << endl;
- word_count = 0;
- }else if(word_count > 1){
- cout << "\tFound in \"" << searchFiles[i] << "\" at line " << line_count
- << " (" << word_count << " times)" << endl;
- word_count = 0;
- }
- }line_count = 0, word_count = 0, f.close();
- }else{ cout << "Could not open file." << endl;}
- }
- if (!word_found){
- cout << keyword << ":" << endl;
- cout << "\t not found" << endl;
- }
- }
- void makeIndex(vector<string> files);
- int main(int argc, char** argv){
- if (argc < 2){
- cout << "No keywords provided." << endl;
- return -1;
- }
- vector<string> txtFiles = filesToSearch();
- if (txtFiles.size() < 1) cout << "No txt files to search." << endl, exit(0);
- if (strcmp(argv[1],"--make-index") == 0){
- cout << "ter" << endl;
- }else{
- for (int i = 0; i < argc-1; i++){
- searchFiles(txtFiles, argv[i+1]);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement