[英]C++: Linux code does not work on Windows - piping data to program
我正在寻找一些从命令行将文件(16位带符号小尾数整数原始数据)通过管道传输到我的程序的帮助:
cat rawdata.dat | myprogram
该代码在Linux上运行良好,每循环一圈将512字节转换为256个整数。
如果我在Windows上使用MinGW进行编译,则只有前76个值会正确转换。 此外,程序在第一个while循环后停止。
有人知道我在做什么错吗? 我正在使用Windows 7 64位+ MinGW编译器。
码:
#include <iostream>
using namespace std;
int main()
{
int BUF_LEN = 512;
char buf[BUF_LEN];
while(!cin.eof())
{
cin.read(buf, BUF_LEN);
int16_t* data = (int16_t*) buf; //to int
for(int i=70;i<85;i++)
{
cout << i << " " << data[i] << endl;
}
}
return 0;
}
测试文件: http : //www.filedropper.com/rawdata
正确的值是:
70 -11584
71 13452
72 -13210
73 -13331
74 13893
75 10870
76 9738
77 6689
78 -253
79 -1009
80 -16036
81 14253
82 -13872
83 10020
84 -5971
TL; DR:
固定? 没有一个。 您必须强制cin进入二进制模式。 我认为这样做必须关闭并重新打开cin,而我只能看到结局很差。
真正的解决方案是不这样做。 正常打开文件
std::ifstream in("rawdata.dat", std::fstream::binary);
其余故事:
怀疑这将是某种愚蠢的二进制翻译,因此我整理了一下代码,以查看文件中发生了什么。
#include <iostream>
#include <fstream>
using namespace std;
#define BUF_LEN 512
int main()
{
ifstream in("rawdata.dat");
char buf[BUF_LEN];
int16_t test;
int count = 0;
while(in.read((char *)&test, sizeof(test)))
{
cout << count++ << ":" << in.tellg() << ":" << test << endl;
if (count == 85)
{
break;
}
}
return 0;
}
重要输出(int16数字:文件中的位置:读取的数字
0:358:0
返回的第一个值实际上位于位置358。不知道为什么。
75:508:10870
76:510:9738
77:909:8225
78:911:11948
的Wooo-EEE! 看一下那个位置,从510跳到909。讨厌。 510恰好位于缓冲区的末尾,但是看起来缓冲区似乎没有受到尊重。
我的理解是istream :: read应该完全没有格式,只是输入流的哑副本到提供的缓冲区,所以我不知道为什么会发生这种情况。 也许窗户很奇怪。
附录
托马斯·马修斯(Thomas Matthews)可能有正确的主意,秘密的Windows控制字符,但是510是一个无害的逗号。 为什么要逗逗逗号?
这个终于解决了我的问题:
如果您使用的是MinGW,只需在代码中添加以下几行:
#include <io.h>
#include <fcntl.h>
#include <fstream>
_setmode(_fileno(stdin), _O_BINARY);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.