I am trying to modify some code that was written in lecture to develop a program that simulates rgrep. The aim of the project is to search a directory's files for a string and output the line it occured on. The problem I'm having is I'm not sure what to put in the ifstream to open of the files in the directory. This is what I have so far:
/*
* Purpose: This program lists the occurences of a user-specified string. In addition
all occurences of the string will be counted and their occurences totaled
along with the number of files that contain the string.
* Date: Apr 08, 2012
*/
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime> // ctime_s()
#include <io.h> // _findfirst, etc.
using namespace std;
vector<string> wordsFound;
vector<string> scan( string const& keyword, string const& filespec, string startDir, bool isRecursive )
{
intptr_t hFile;
_finddata_t fd;
string line;
unsigned lineCount = 0;
//vector<string> wordsFound;
// fix directory name
if( !startDir.empty() )
{
char last = startDir.back();
if( last != '/' && last != '\\' && last != ':' )
startDir += '/';
}
string findPath = startDir + filespec;
hFile = _findfirst( findPath.c_str(), &fd );
ifstream in( );
while( getline( in, line ) ) {
++lineCount;
if( line.find( keyword ) != string::npos ){
//++keywordCount;
wordsFound.push_back(line);
//cout << lineCount << "\t" << line << '\n';
}
}
if( (hFile = _findfirst( findPath.c_str(), &fd )) == -1L )
{
cout << "No " << filespec << " files in current directory." << endl;
return wordsFound;
}
do {
if( isRecursive &&
(fd.attrib & _A_SUBDIR) &&
fd.name != string(".") &&
fd.name != string("..") )
{
string subDir = startDir + fd.name ;
scan( keyword, filespec, subDir, isRecursive );1
}
} while( _findnext( hFile, &fd ) == 0 );
_findclose( hFile );
return wordsFound;
}
int main( int argc, char *argv[] ) {
locale here("");
cout.imbue( here );
vector<string> args;
for( int i = 0; i < argc; ++i )
args.push_back( argv[i] );
string keyword, inputFile, line;
unsigned lineCount = 0;
//if only the string is provided
if ( args.size() == 1 ) {
cin >> keyword;
scan( keyword, "*.*", "..", false );
cout << wordsFound.size() << endl;
/*for( unsigned i = 0; i < wordsFound.size(); ++i ) {
cout << wordsFound[i] << endl;
}*/
}
}
Any help is appreciated.