从命令行c ++发送文本文件名

Kum*_*wal 0 c++ command-line file c++11

我想运行我的代码并以两种方式发送我的文件

  1. myprogram < input.txt 要么 cat input.txt | myprogram
  2. myprogram input.txt

我已经找到了使用的方式argc,argv[]但我无法弄清楚如何编写第一个选项的代码.

int main (int argc, char *argv[])
{
     ifstream fin;
     if(argc > 1){

        fin.open (argv[1]);
     }
     else
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ica 5

正如上面评论中所提到的,一种可移植的方式是传递打开的文件或std::cin作为istream对函数的引用并在那里进行输入.在这种情况下,文件或std::cin可以传递.例如

#include <iostream>
#include <fstream>
#include <string>

void readinfo (std::istream& in)
{
    std::string s;
    while (in >> s)
        std::cout << s << '\n';
}

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

    if (argc > 1) {     /* read from file if given as argument */
        std::ifstream fin (argv[1]);
        if (fin.is_open())
            readinfo (fin);
        else {
            std::cerr << "error: file open failed.\n";
            return 1;
        }
    }
    else {  /* read from stdin */
        readinfo (std::cin);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

/dev/stdin如果没有给出文件,则从非便携式Linux读取选项仅需要三元运算符,例如

    std::ifstream fin (argc > 1 ? argv[1] : "/dev/stdin");
    if (!fin.is_open()) {
        std::cerr << "error: file open failed.\n";
        return 1;
    }
    /* read from fin here */
Run Code Online (Sandbox Code Playgroud)

两者都不是完全优雅,但都支持(受操作系统限制)

myprogram < input.txt
Run Code Online (Sandbox Code Playgroud)

要么

myprogram input.txt
Run Code Online (Sandbox Code Playgroud)