【问题标题】:Re-direct binary file content from STDIN into a C program将二进制文件内容从 STDIN 重定向到 C 程序
【发布时间】:2021-01-21 07:20:21
【问题描述】:

所以我正在像这样在命令提示符下向 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;
}

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

【问题讨论】:

  • 嘿,我没有使用 fopen,因为内容在 CMD 中通过管道传输到 STDIN。我只需要阅读我在 fread 中所做的标准输入。读取的样本输出字节数 = 2727,然后程序停止。但是管道文件有更多字节要读取
  • 如果打开文件而不是管道会发生什么?
  • 这很好,但我必须从 STDIN 读取管道内容,这就是我的用例。它不工作
  • 如果你像标签建议的那样使用 Windows,你需要弄清楚如何以二进制模式重新打开标准输入。
  • @Shawn 非常感谢你,这正是我的场景。它现在可以工作了,非常感谢你,你救了我的一天

标签: c windows file


【解决方案1】:

如果您可以在您的解决方案中包含batch file,即将文件的内容提供给shell 变量,然后使用shell 变量作为可执行文件的命令行参数,那么以下步骤将起作用:

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

注意:除非somebinaryfile.bin位置列在path环境变量中,否则应包括&lt;path&gt;,例如:C:\dir1\dir2\somebinaryfile.bin

  • 然后从命令行执行:

    read.bat

注意,您需要在main() 函数的开头将stdin 设置为二进制模式。例如使用_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);
}

典型会话的收益:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-07
    • 2016-05-27
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多