简体   繁体   English

Windows管道到C ++程序

[英]windows piping to a c++ program

I have the following c++ program: 我有以下c ++程序:

#include <iostream>
using namespace std;

//will find the last dot and return it's location
char * suffix_location(char *);

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cout << "not enough arguments!" << endl;
        for (int i = 0; i < argc; i++)
            cout << argv[i] <<endl;
        exit(1);
    }
    //ignore first parameter (program name).
    argv ++;
    argc --;

    //the new suffix
    char * new_suffix = argv[0];

    argv++;
    argc--;

    for (int i = 0; i < argc; i++)
    {
        char * a = suffix_location(argv[i]);
        if (a != NULL)
        {
            a[0] = NULL;
            cout << argv[i] << '.' << new_suffix << endl;
        }
    }
    return 0;
}

char * suffix_location(char * file_name)
{
    char * ret = NULL;
    for (; * file_name; file_name++)
        if (*file_name == '.')
            ret = file_name;
    return ret;
}

I compiled it using the following command: 我使用以下命令对其进行了编译:

cl /EHsc switch_suffix.cpp

when I run 当我跑步时

switch_suffix py a.exe b.txt

I get: 我得到:

a.py
b.py

as expected. 如预期的那样。
the promblem start when I try to pipe. 当我尝试管道操作时,问题就开始了。 running the following: 运行以下命令:

dir /B | swich_suffix py 

results nothing, and running 没有结果,并且运行

 dir /B | swich_suffix py 

results: 结果:

not enough arguments!
switch_suffix

The piping on the system works fine - I tried it on a few other programs. 系统上的管道运行良好-我在其他一些程序上进行了尝试。
I tried creating a vs project and compiling the code from there - helped nothing. 我尝试创建一个vs项目并从那里编译代码-没有任何帮助。

whats wrong, and hoe can I fix it? 怎么了,头可以解决吗?

I'm running on win7, using vs2010 tools. 我正在使用vs2010工具在win7上运行。

进行管道传输时,传递给程序的信息位于stdin上,而不是argv上

When you pipe to another program it goes to the standard input and not to the arguments in main. 当您通过管道传输到另一个程序时,它将转到标准输入,而不是main中的参数。

This piece of code prints out what it receives on stdin to stdout , try this: 这段代码将在stdin上收到的内容打印到stdout ,请尝试以下操作:

for (std::string line; std::getline(std::cin, line);) {
      std::cout << line << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM