从Win32上的stdin读取二进制数据,并将其写入文件

时间:2014-01-09 21:54:44

标签: windows console pipe

什么是Unix管道的Windows(Win32)命令行等价物:

myprog myarg | cat >out.dat

请注意我想要一个管道来测试myprog是否可以成功写入管道,所以请不要简化它:

myprog myarg >out.dat

我想像是

myprog myarg | copy /b con out.dat

可行,但我没有Windows机器可以查看。

请注意,生成的数据是二进制的,它包含所有可能的字节值0 ... 255,并且所有这些都必须保持原样,不进行任何转换。

2 个答案:

答案 0 :(得分:6)

由于Windows没有附带这样的程序,因此这是C中的快速程序。

#include <stdio.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    char buffer[16384];
    int count;
    _setmode(_fileno(stdin), _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
    while ((count = fread(buffer, 1, sizeof(buffer), stdin)) != 0)
        fwrite(buffer, 1, count, stdout);
    return 0;
}

您可以轻松修改它以写入您选择的文件,而不是stdout

答案 1 :(得分:4)

Windows中没有内置任何内容,与您在给出的示例中使用cat的方式相同。您建议的命令(copy /b con)当然不起作用,因为con是控制台设备,而不是标准输入。

您可以尝试GNU utilities for Win32,其中包含cat的端口。否则你可能需要编写自己的代码,这当然很简单。

相关问题