将 int 的二进制文件读取到字符串 c++

Reading binary file of int to string c++

本文关键字:字符串 c++ 读取 二进制文件 int      更新时间:2023-10-16

我在读取二进制文件时遇到问题。当我读取包含字符串的二进制文件时,它可以完美读取。但是当我尝试读取看起来像这样的文件时:

1830 3030 3030 3131 3031 3130 3000 0000
0000 0000 0000 0000 1830 3030 3030 3131
3030 3030 3100 0000 0000 0000 0000 0000
1830 3030 3030 3131 3030 3131 3000 0000
0000 0000 0000 0000 1830 3030 3030 3131
3031 3030 3000 0000 0000 0000 0000 0000
1830 3030 3030 3131 3031 3131 3100 0000
0000 0000 0000 0000 1830 3030 3030 3131
3130 3130 3100 0000 0000 0000 0000 0000 ... and so on 

它只读取其中的一部分。这是我用于读取二进制文件并将其转换为字符串的代码。

string toString (const char *c, int size);
int main(int argc, char* argv[]) 
{
    streampos size;
    char * memblock;
    ifstream file (argv[1], ios::in|ios::binary|ios::ate);
    size = file.tellg();
    memblock = new char[size];
    file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();
    string input = toString(memblock,size);
    cout << input << endl; //this prints just portion of it 000001101100
    return 0;
}
string toString (const char *c, int size)
{
    string s;
    if (c[size-1] == '')
    {
        s.append(c);
    }
    else 
    {
        for(int i = 0; i < size; i++)
        {
            s.append(1,c[i]);
        }
    }
    return s;
}

但是当我尝试读取 0 和 1 的 txt 文件时,它读起来很好。我对 c++ 很陌生,我不太确定为什么会这样。

你的问题是你正在使用cout .这旨在打印人类可读的字符串,而不是二进制。所以你标记的那行:

cout << input << endl; //this prints just portion of it 000001101100

只会打印其中的一部分。

您提供的二进制数据是:

1830 3030 3030 3131 3031 3130 3000 0000

以下是数据第一行的 ASCII:

<CAN> "000001101100" <NUL> <NUL> <NUL>

第一个<CAN>0x18 - <NUL>具有0的值 - 这就是cout停止的地方:它打印人类可读的ASCII值,直到遇到0 - 您的数据充满了它们。

您需要打印字符的十六进制值 - 这是一个更复杂的过程。