【问题标题】:Writing/Reading strings in binary file-C++在二进制文件中写入/读取字符串-C++
【发布时间】:2015-06-04 13:39:11
【问题描述】:

我搜索了类似的帖子,但找不到可以帮助我的帖子。

我正在尝试先写入包含 String 的字符串长度的整数,然后将字符串写入二进制文件中。

但是,当我从二进制文件读取数据时,我读取 value=0 的整数并且我的字符串包含垃圾。

例如,当我输入“asdfgh”作为用户名并输入“qwerty100”作为密码时 我得到两个字符串长度的 0,0,然后我从文件中读取垃圾。

这就是我将数据写入文件的方式。

std::fstream file;

file.open("filename",std::ios::out | std::ios::binary | std::ios::trunc );

Account x;

x.createAccount();

int usernameLength= x.getusername().size()+1; //+1 for null terminator
int passwordLength=x.getpassword().size()+1;

file.write(reinterpret_cast<const char *>(&usernameLength),sizeof(int));
file.write(x.getusername().c_str(),usernameLength);
file.write(reinterpret_cast<const char *>(&passwordLength),sizeof(int));
file.write(x.getpassword().c_str(),passwordLength);

file.close();

在我读取数据的同一个函数的正下方

file.open("filename",std::ios::binary | std::ios::in );

char username[51];
char password[51];

char intBuffer[4];

file.read(intBuffer,sizeof(int));
file.read(username,atoi(intBuffer));
std::cout << atoi(intBuffer) << std::endl;
file.read(intBuffer,sizeof(int));
std::cout << atoi(intBuffer) << std::endl;
file.read(password,atoi(intBuffer));

std::cout << username << std::endl;
std::cout << password << std::endl;

file.close();

【问题讨论】:

  • 你的阅读方式应该反映你的写作方式。您没有编写长度的字符串表示形式,因此没有理由尝试像那样阅读它。

标签: c++ string binaryfiles


【解决方案1】:

在读回数据时,您应该执行以下操作:

int result;
file.read(reinterpret_cast<char*>(&result), sizeof(int));

这会将字节直接读取到result 的内存中,而不会隐式转换为int。这将首先恢复写入文件的确切二进制模式,从而恢复您原来的 int 值。

【讨论】:

  • 注意:注意字节序不匹配问题,例如如果文件是由 PowerPC 机器写入并由 Intel 机器读取,反之亦然。
【解决方案2】:
file.write(reinterpret_cast<const char *>(&usernameLength),sizeof(int));

这会从 &usernameLength; 写入 sizeof(int) 个字节。这是整数的二进制表示,取决于计算机架构(小端与大端)。

atoi(intBuffer))

这会将 ascii 转换为整数并期望输入包含字符表示。例如intBuffer = { '1', '2' } - 将返回 12。

你可以试着用你写的同样的方式来阅读它-

*(reinterpret_cast<int *>(&intBuffer))

但它可能会导致未对齐的内存访问问题。更好地使用 JSON 等序列化格式,这将有助于以跨平台的方式阅读它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多