用cat将数据文件管道化为C++程序

fux*_*uxT 5 c++ pipe cat

我正在寻找一些帮助从命令行管道文件(16位带符号的小端整数原始数据)到我的程序:

cat data.dat | myprogram
Run Code Online (Sandbox Code Playgroud)

然后它应该将数据转换为16位有符号整数.它适用于前12个值.第13个值是错误的,后跟零.

第二个问题是程序似乎只进入while循环一次.

我正在使用Windows + MinGW.

我的代码:

#include <iostream>
using namespace std;

#define DEFAULT_BUF_LENGTH (16 * 16384)

int main(int argc, char* argv[]) 
{
    char buf[DEFAULT_BUF_LENGTH];

    while(cin >> buf) 
    {
        int16_t* data = (int16_t*) buf; //to int

        for(int i=0;i<18;i++)
        {
            cout << data[i] << endl;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0
9621
-14633
-264
5565
-12288
9527
-7109
11710
6351
4096
-5033
5773
147
0
0
0
0
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Ale*_*bin 5

您可能会尝试使用read()而不是>>运算符,后者通常用于格式化输入。另外,检查实际读取了多少数据也很有用:

#include <iostream>
using namespace std;

#define DEFAULT_BUF_LENGTH (16 * 16384)

int main(int argc, char* argv[]) 
{
    char buf[DEFAULT_BUF_LENGTH];

    for(;;) 
    {
        cin.read(buf, sizeof(buf));
        int size = cin.gcount();
        if (size == 0) break;

        int16_t* data = (int16_t*) buf; //to int

        for(int i=0;i<size/sizeof(int16_t);i++)
        {
            cout << hex << data[i] << endl;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)