c - 将二进制文件内容从 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;
}
我提供一个图像文件作为输入。问题是程序在读取几个字节后终止。但如果我提供一个文本文件,它似乎工作正常。我应该改变什么,以便我的程序可以正确读取管道图像文件内容
解决方案
如果您可以在您的解决方案中包含一个批处理文件,即将文件的内容输入到 shell 变量中,然后使用 shell 变量作为可执行文件的命令行参数,那么以下步骤将起作用:
- 将其复制到批处理文件中,例如
read.bat
:
set /p in= < somebinaryfile.bin
CProgram.exe "%in%"
注意:除非somebinaryfile.bin
location 在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);
}
推荐阅读
- node.js - 无法从 lambda 发送 Firebase 推送通知
- asp.net-mvc - 在 ASPNET.Core 3.1 中扩展 AspnetUserRoles 表的正确方法是什么?
- ssis - SSIS - 为什么从 excel 文件导入包含所有可能的行?
- r - n 个不同的最高/最低值的最小值、最大值、平均值,并将它们与时间序列数据一起绘制在 R 中的同一图表上
- ios - 不能在属性初始化程序中使用实例成员“userCard1”;属性初始化程序在“自我”可用之前运行错误
- git - 如何切换 github 账号并追溯更新提交历史?
- python-3.x - 我可以让 Python 使用 if 语句检查我的列表以查看用户输入是否包含我的列表中的字符串吗?如果没有,还有其他选择吗?
- c# - 我可以在 DAC 扩展中使用 PXDBScalar 从同一个表中查询记录吗?
- mysql - JSON_EXTRACT() 查询返回 NULL
- python - 无法使用 python pyside2 在托盘菜单中创建自定义小部件