程序正在生成空白输出文件

Program making blank output file

本文关键字:空白 输出 文件 程序      更新时间:2023-10-16

所以我一直在开发一个类似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 argumentsn"
            "Usage: grepn";
    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 << ".txtn";
   //         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();
}

当我运行它时,它会生成文件,但文件最终为空,我确信我要搜索的内容在文件中,所以我想我在这里的某个地方犯了逻辑错误。我没有任何制作输出文件的经验,但我所写的内容似乎与我所读的内容的语法相匹配。你们能给我的任何建议都将不胜感激。

看看下面两行,为什么要先调用构造函数,然后再调用open?

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

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