首页 > 解决方案 > 将二进制文件内容从 STDIN 重定向到 C 程序

问题描述

所以我像这样在命令提示符下向 c 程序提供文件内容。例如-类型“文件名”| C程序.exe。键入命令获取文件的内容并将其提供给我的 cporgram.exe

代码::

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

# define CACHE 102400

int main(int argc, char* argv[])
{
    
    char *buf = malloc(CACHE * sizeof(char));
    FILE* f = fopen("out.txt", "wb");
    size_t bytesread;

    while(bytesread = fread(buf, sizeof(char), CACHE, stdin))
    {
        printf("bytes read = %zu\n", bytesread);
        fwrite(buf, bytesread, 1, f);
    }
    
    return 0;
}

我提供一个图像文件作为输入。问题是程序在读取几个字节后终止。但如果我提供一个文本文件,它似乎工作正常。我应该改变什么,以便我的程序可以正确读取管道图像文件内容

标签: cwindowsfile

解决方案


如果您可以在您的解决方案中包含一个批处理文件,即将文件的内容输入到 shell 变量中,然后使用 shell 变量作为可执行文件的命令行参数,那么以下步骤将起作用:

  • 将其复制到批处理文件中,例如read.bat
    set /p in= < somebinaryfile.bin
    CProgram.exe "%in%"

注意:除非somebinaryfile.binlocation 在path环境变量中列出,否则它应该包括<path>,例如:C:\dir1\dir2\somebinaryfile.bin

  • 然后从命令行执行:

    读取.bat

请注意,您需要在函数stdin开始时设置为二进制模式。main()例如使用_setmode(_fileno(stdin), O_BINARY);

我的测试代码发布在这里(注意:它没有经过全面测试,但可以从标准输入读取二进制文件并将二进制内容传输到新文件。)

Windows10,使用 GNU GCC 编译器

#include <windows.h>
#include <io.h> // _setmode()
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> // O_BINARY
#include <time.h>

void make_binary(void);

int main(int argc, char *argv[])
{
    _setmode(_fileno(stdin), O_BINARY);//sets stdin mode to binary 

    //make_binary();//used to produce binary file for testing input
                    //comment after first use.

    FILE *fp = fopen(".\\new_binary.bin", "wb");
    if(fp)
    {
        fwrite(argv[1], sizeof(unsigned char), 1000, fp);
        fclose(fp);
    }
    return 0;
}

//Create some binary data for testing
void make_binary(void)
{
    FILE *fp = fopen(".\\binary.bin", "wb");
    unsigned char bit[1000];
    srand(clock());
    for(int i=0; i< 1000; i++)
    {
        bit[i] = (unsigned char)rand();
    }
    size_t count = fwrite(bit, sizeof(*bit), 1000, fp);
    printf("Number of bytes written to binary.bin = %u\n", count);
    fclose(fp);
}

典型会话的收益:
在此处输入图像描述


推荐阅读