c++ - 制作空白输出文件的程序

标签 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();
}

当我运行它时,它生成了文件,但文件最终是空白的,我确定我要搜索的内容在文件中,所以我想我在这里某处犯了逻辑错误。我没有制作输出文件的经验,但我写的似乎与我读过的语法相符。你们能提供的任何建议都将不胜感激。

最佳答案

看下面两行,为什么先调用constructor再调用open?

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

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

关于c++ - 制作空白输出文件的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9695262/

相关文章:

C++ - For 循环有时不会停止 - 多线程

c++ - 使用对象作为键时保持 std::map 平衡

c# - MVVM 从文本文件中获取数据

python - 导入错误 :cannot import name get_model

file - 实现文件系统的基础

c++ - 使用 SDL 的硬件缓冲,关于它如何工作的问题

c++ - 重载 >> 运算符

c++ - C++11 std::map 程序无法在 clang 3.4 中编译

python - 在 python 中复制(重复)文件

java - 如何同时打印到文件和显示器?