C++ 将文件名输入重定向转换为新的输出文本文件,并在新输出文件的名称后附加 .txt

C++ Convert filename input redirection to new output text file with .txt appended to name of new output file

我正在尝试使用输入重定向来扫描文件中的正则表达式,并将这些正则表达式与文件的行号一起输出到新的输出文本文件。输出文本文件是用于输入重定向的文件的名称,并附加“.txt”。例如,如果程序是 运行 如下:

./scanRegex < scanThisFile.log

那么输出文件应该叫

scanThisFile.log.txt

我创建了一个简单的程序如下(减去正则表达式扫描到 找出问题)。

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

当我使用

argv[ 0 ]

程序 运行s 但是文件名对于我的意图是错误的但是可以理解,因为程序名称是 argv 的第一个参数: a.txt

当我使用

argv[ 1 ]

我得到以下运行时间错误:

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)

当我使用

argv[2]

程序 运行s 但文件名错误且充满乱码(溢出?):

也许这只是我的问题的一部分。任何帮助都会 大大地 赞赏。 谢谢。

您将 标准输入 与程序的 命令行参数 混淆了。命令行参数是调用程序时包含在命令行中的字符串列表。例如:

$ ./myProgram arg1 arg2 ... argn

这些是通过argvargc读取的,它们分别代表“参数向量”和“参数计数”。按照惯例,第一个参数是程序的工作目录。在此示例中,您将拥有:

argv == {"/path/to/myProgram", "arg1", "arg2", ..., "argn"}
argc == n

main 的开头。与任何原始数组一样,您必须小心不要通过检查 argcargv 读取越界。

另一方面,标准输入是提供给程序数据流在整个 main 的调用中。这是使用 std::cin.

读取的
int main(int argc, char** argv){
    std::string s;
    std::cin >> s; // read from standard input
}

当你运行这个程序时,它会阻塞在指定的行,直到它从标准输入接收到数据。当程序从命令行 运行ning 时,可以通过手动键入来提供此数据:

$ ./myProgram

hello

或通过输入重定向:

$ echo "hello" | ./myProgram

$ ./myProgram < hello.txt

在上面的三个示例中,s 将包含输入文本的第一个单词,您可以在下一行中将其用于任何您想要的内容。

请注意,std::cin >> s 将读取文本,直到它到达第一个白色-space 字符。幸运的是,有一些简单的方法可以 read an entire line from stdin and to read everything from stdin