Take the 2-minute tour ×

So I've been working on a grep like program. That will search a given file and then return all lines with instances of the word you want with the along witht he line number of where it occured. I came up with this :

#include <iostream>
#include <regex>
#include <string>
#include <fstream>
#include <vector>
#include <regex>
#include <iomanip>

using namespace std;


// validate the command line info
if( argc < 2 ) {
    cout << "Error: Incorrect number of command line arguments\n"
            "Usage: grep\n";
    return EXIT_FAILURE;

//Declare the arguments of the array
string query = argv[1]; 
string inputFileName = argv[2];
string outFileName = argv [3];
regex reg(query);

// Validate that the file is there and open it
ifstream infile( inputFileName );
if( !infile ) {
    cout << "Error: failed to open <" << inputFileName << ">\n"
            "Check filename, path, or it doesn't exist.\n";
    return EXIT_FAILURE;

 ofstream outFile (outFileName);
 outFile.open( outFileName + ".txt" );
// if( !outFile ){
  //          cout << "Error: failed to create output file at " << outFileName << ".txt\n";
   //         return EXIT_FAILURE;
 //   }

//Create a vector of string to hold each line
vector<string> lines;

//Create a while loop that puts each line into the vector lines
string currentLine = "";
int currentLineNum = 0;

    lines.push_back( currentLine ); 
            if( regex_match( query, reg ) )
                    outFile << "Line " << currentLineNum << ": " << currentLine;


When I run it it makes the file but the files end up blank, I'm sure what I'm searching for is in the file, so I imagine I've made a logic error somewhere here. I don't have any experience with making output files, but what I wrote seemed to match the syntax of what I've read. Any advice you guys can give would be greatly appreicated.

share|improve this question
Did you try using a debugger? –  Carl Norum Mar 14 '12 at 2:53
Just the general Visual Studio debugger, no errors showed. –  Sh0gun Mar 14 '12 at 2:55
No errors showed? What does that mean? Clearly there is an error, or your program would be working, right? –  Carl Norum Mar 14 '12 at 2:55
That's not a debugger. You're talking about error messages from the compiler. Those aren't going to help you with runtime problems. –  Carl Norum Mar 14 '12 at 2:57
Do you realize that argv[1] is grep.cpp and argv[2] is include according to your comment? (and out.txt becomes out.txt.txt)? –  Jesse Good Mar 14 '12 at 3:16

1 Answer 1

Look at the following two lines, why are you calling constructor and then calling open?

ofstream outFile (outFileName); // This does same thing as member function open
outFile.open( outFileName + ".txt" ); // <-- remove this line unnecessary 

The second line will fail and set failbit, so the stream is in a bad state (also, you have out.txt.txt).

share|improve this answer

Your Answer


