gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:54:13 27 4
gpt4 key购买 nike

我现在尝试将一些整数值写入文件,然后使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com