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

标签 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;
}

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

最佳答案

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;
} 

关于C++ fstream - 无法使用二进制格式从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718084/

相关文章:

c++ - 将 2 个结构数组的信息输出到一个文件中

c++ - 并发修改整数中的位

c++ - 如何访问指向映射的指针的元素?

c - 在 C 中进行二进制算术的最佳方法?

mysql - 如何计算具有二进制格式的数字的汉明距离

c++ - 如何使用单个 fstream 创建、读取和写入文件

c++ - fstream 没有匹配的调用函数错误

c++ - 您可以在不使用 Core Audio API 的情况下更改 Windows 中 volume mixer/sndvol 中列出的程序名称吗?

c++ - 我可以从 constexpr 函数返回一个可选值吗?

c++ - 设置一个等于 369 的字符给出与 113 相同的二进制模式是 UB 行为吗?