Word search in multiple files

What would be the best way to search for a key word in multiple files? I am having trouble figure out the best structure to use, how to separate one word at a time from a file and iterate one file after another.

Thanks
At a minimum, you are going to need code to get a list of files to search.

Then, you'll need a loop to open each file:
You are going to need code to open each file in your list.

You'll need code to read the file and compare each "word" to the key word.


You didn't specify if you are going to handle file patterns the user might specify, like all files that end in .c, etc. Also, you probably want to open the files in text mode (as opposed to binary.) There can be a lot to this, but I hope this helps you get the creative juices flowing!
Last edited on
I can open the files just fine, however, I have 50 .text files and the exact names of each. I am confused how to loop through them. Can they be stored into an array?
You could use a vector<string> to store the filenames, and then just iterate through it. A nice way to populate the vector could be to use the command prompt arguments.
This what I have now. It will open a file and output what is in it but then I added the for loop to iterate through sequential files: file01, file02, file03.... so why doesn't it work they way I have it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;

int main()
{
   
   string x;
   ifstream inFile;

   for (int i = 01; i<=50; i++ )
   {
   
   inFile.open("file" << [i] <<);


   if (inFile.is_open())
   {
   while (inFile.good())

       {
       getline(inFile, x);
       cout << x << endl;
       }

       inFile.close();
    }
   else cout << "Unable to open file\n";

   }
 return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iomanip>
#include <sstream>
#include <fstream>

inline std::string to_string( int v )
{
    std::ostringstream stm ;
    stm << std::setw(2) << std::setfill('0') << v ;
    return stm.str() ;
}


int main()
{
    constexpr const char* path_prefix = "file" ;
    // const char* const path_prefix = "file" ; // 1998

    enum { NUM_FILES = 50 } ;

    for( int i = 0 ; i < NUM_FILES ; ++i )
    {
        std::ifstream file( path_prefix + to_string(i) ) ;
        // std::ifto_stringeam file( ( path_prefix + to_string(i) ).c_str() ) ; // 1998

        std::string line ;
        while( std::getline( file, line ) )
        {
            // do whatever with the line
        }
    }
}
Topic archived. No new replies allowed.