程序制作空白输出文件

时间:2012-03-14 02:50:16

标签: c++ file

所以我一直在研究类似grep的程序。这将搜索给定的文件,然后返回包含所需单词实例的所有行,并带有它出现位置的行号。我想出了这个:

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

using namespace std;

int main (int argc, char* argv[]){

// 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;

while(getline(infile,currentLine))
{
    lines.push_back( currentLine ); 
            currentLineNum++;
            if( regex_match( query, reg ) )
                    outFile << "Line " << currentLineNum << ": " << currentLine;



}
    outFile.close();
    infile.close();
}

当我运行它时它会生成文件,但文件最后是空白的,我确定我正在搜索的是文件中的内容,所以我想我在这里某处出现了逻辑错误。我没有任何制作输出文件的经验,但我写的内容似乎与我读过的语法相符。你们给予的任何建议都会有很大的意义。

1 个答案:

答案 0 :(得分:1)

请看以下两行,为什么要调用构造函数然后调用open?

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

第二行将失败并设置failbit,因此流处于错误状态(同样,你有out.txt.txt)。