I am trying to use input redirection to scan a file for regular expressions and output those regular expressions with the line number of the file to a new output text file. The output text file is to be the name of the file that was used for the input redirection with ".txt" appended to it. For instance if the program was run as follows:
./scanRegex < scanThisFile.log
Then the output file should be called
scanThisFile.log.txt
I created a simple program as follows ( minus the regex scanning to isolate the issue ).
main.cpp
#include <iostream>
#include <ios>
#include <fstream>
#include <string>
#include <vector>
int main( int argc, char* argv[] )
{
std::string fileName = argv[1]; //<---===== ??????
std::string txt = ".txt\n";
char outputFile[100];
for( int i = 0; i < fileName.length(); ++i ){
outputFile[i] = fileName[i];
}
for( int i = fileName.length(); i < fileName.length() + 4; ++i ){
outputFile[i] = txt[i - fileName.length()];
}
std::ofstream outfile;
outfile.open(outputFile);
outfile << "It works!!";
outfile.close();
}
When I use
argv[ 0 ]
the program runs but the filename is wrong for what my intention is but is understandable because the program name is the first argument for argv: a.txt
When I use
argv[ 1 ]
I get the following runtime error:
osboxes@osboxes:~/Desktop/ps7$ ./a < device1_intouch.log terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid Aborted (core dumped)
When I use
argv[2]
the program runs but the filename is wrong and full of gibberish (overflow?):
Maybe this is only part of where my problem is. Any help would be greatly appreciated. Thank you.