c++ - 为什么我的程序无法正确读取二进制文件?
问题描述
当我读取二进制文件时,它什么也没有读取……这是读数:
if (file.is_open())
{
Challenge* newChallenge;
while (!file.eof())
{
file.read((char*)&newChallenge, sizeof(Challenge));
if (!challenges.contains(newChallenge))
{
challenges.push_back(newChallenge);
}
}
delete newChallenge;
std::cout << "Successfully loaded " << fileName << std::endl;
file.close();
}
这是写作:
else if(action == "write"){
std::ofstream file("Challenges.bin", std::ios::binary);
if(file.is_open()){
for (size_t i = 0; i < challenges.length(); i++)
{
file.write((char*)&challenges[i], sizeof(Challenge));
}
std::cout << "Successfully written to file!" << std::endl;
}else {
std::cout << "Failed to open file!" << std::endl;
}
file.close();
}
这是挑战课:
#ifndef CHALLENGE_H
#define CHALLENGE_H
#include "String.h"
class Challenge
{
private:
double rating = 0;
int status = 1, finishes = 0;
String init;
public:
Challenge(String _init = "") : init(_init) {}
void addToStatus() { status++; }
void addToRating(double rate)
{
finishes++;
rating = ((rating * (finishes - 1)) + rate) / finishes;
}
String getChallenge() { return init; }
int getStatus() { return status; }
double checkRating() { return rating; }
};
#endif
注意:String 类是我自己使用 char* 制作的类,它不是来自 std..。我不允许使用 std 类。
解决方案
Challenge* newChallenge;
while (!file.eof())
{
file.read((char*)&newChallenge, sizeof(Challenge));
...
这段代码声明了一个指向类实例的指针,该指针未初始化为指向任何东西,然后显然想从磁盘文件中读取一些字节。
这至少在三个层面上是非常非常错误的:
- 你没有分配任何内存
- 对象不是字节块,要创建它们,您需要调用构造函数
- 读数针对的是指针,而不是指向的内存(调用
&
中有多余的fread
)
推荐阅读
- python - 如何使用 Python 将条带产品从“测试”复制到“现场”?
- python - Model.clean() 与 Model.clean_fields()
- python - 如何加快查找组合的函数的处理时间?
- python - 如何在python中使用tktinter通过页面传递变量
- c++ - gtkmm3.0 和 Css:GtkButton 状态的活动状态选择器不应用更改
- javascript - 滚动时使用 Bodymovin 和 Scrollmagic 制作动画
- excel - 如何优化数字组合的 vba 代码
- laravel - Laravel 修改密码问题
- jquery - 根据嵌套标签中的文本选择 Selenium 元素
- html - 如何在 webXR 相机视图上覆盖 HTML 文本/按钮?