简体   繁体   中英

Reading binary file of int to string c++

I have problem with reading my binary file. When I read binary file that contains strings it reads perfectly. But when I try read file that looks something like this:

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 

it reads just portion of it. This is my code for reading and converting the binary file to string.

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] == '\0')
    {
        s.append(c);
    }
    else 
    {
        for(int i = 0; i < size; i++)
        {
            s.append(1,c[i]);
        }

    }

    return s;
}

But when I try to read txt file of 0 and 1 it reads just fine. I am pretty new to c++, and I'm not quite sure why is that.

Your problem is that you're using cout . This is designed to print human-readable strings, not binary. So the line that you flagged:

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

would only print a portion of it.

The binary data you gave was:

1830 3030 3030 3131 3031 3130 3000 0000

Here is the ASCII for the first line of the data:

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

The first <CAN> is 0x18 - the <NUL> has the value 0 - and that's where cout stops: it prints human-readable ASCII values until it encounters a 0 - your data is full of them.

You need to print the hex values of the characters - a much more involved process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM