C ++ fstream - 无法使用二进制格式从文件中读取

时间:2015-04-18 13:33:14

标签: c++ binary fstream

我现在正在尝试将一些整数值写入文件,然后使用fstream读取它。我正是这样做的:

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>           

typedef unsigned char  BYTE; // 1byte
typedef unsigned short  WORD; // 2bytes
typedef unsigned long  DWORD; //4bytes

using namespace std;

template <typename Word>
ostream& write_word( ostream& outs, Word value )
{
    for (unsigned size = sizeof( Word ); size; --size, value >>= 8)
        outs.put( static_cast <char> (value & 0xFF) );
    return outs;
}

template <typename Word>
istream& read_word( istream& ins, Word& value )
{
    for (unsigned size = 0, value = 0; size < sizeof( Word ); size++)
            value |= ins.get() << (8 * size);   
    return ins;
}   


int main()
{            
    system("CLS");
    int num = 1;                 
    string *str;

    cout<<"How much strings do you want to write: ";
    cin>>num;

    if(num <= 0)
    {                       
        cout<<"\nInvalid value!"<<endl;
        return 1;                
    }

    str = new string[num];

    ofstream out("2.txt",ios::binary|ios::out);

    for(int i = 0; i< num; i++){
        cout<<"Insert string";
        cout<<i;      
        cout<<": ";
        cin>>str[i];

        write_word(out, (DWORD)str[i].length());
        out<<str[i];

    }                               

    out.close();
    cout<<"Values saved to 2.txt."<<endl;

    for(int i = 0; i< num; i++){
        cout<<"string"<<i<<" = "<<str[i]<<endl; 
    }

    system("PAUSE");

    cout<<"Loading values from 2.txt now."<<endl;

    ifstream in("2.txt",ios::binary|ios::in);

    if(!in.is_open()){ cout<<"ERROR"; return 1; }

    for(int i = 0; i< num; i++){
        DWORD len = 0x0;
        read_word(in, len);

        cout<<"string"<<i<<" length is "<<len<<endl;

        char *tmpStr = new char[len];
        in.read(tmpStr, len);
        std::string str2(tmpStr, len);

        cout<<"string"<<i<<" = "<<str2<<endl;
    }

    in.close();    
    system("PAUSE");        

    return 0;
}

写入成功,所以我可以看到文件中的变化,但我无法弄清楚为什么从它读取字符串大小不起作用。字符串大小始终为零,结果字符串为空。

1 个答案:

答案 0 :(得分:3)

for (unsigned size = 0, value = 0; size < sizeof( Word ); size++)在循环范围内声明一个新的value

通过引用value,您正在更改循环中声明的unsigned value,而不是参数。在循环之前将值设置为零。它也更容易阅读和理解。

最终代码:

template <typename Word>
istream& read_word( istream& ins, Word& value )
{
    value = 0;
    for (unsigned size = 0; size < sizeof( Word ); size++)
            value |= ins.get() << (8 * size);   
    return ins;
}