首页 > 解决方案 > 为什么我的程序无法正确读取二进制文件?

问题描述

当我读取二进制文件时,它什么也没有读取……这是读数:

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 类。

标签: c++filebinarybinaryfiles

解决方案


Challenge* newChallenge;
while (!file.eof())
{
    file.read((char*)&newChallenge, sizeof(Challenge));
...

这段代码声明了一个指向类实例的指针,该指针未初始化为指向任何东西,然后显然想从磁盘文件中读取一些字节。

这至少在三个层面上是非常非常错误的:

  1. 你没有分配任何内存
  2. 对象不是字节块,要创建它们,您需要调用构造函数
  3. 读数针对的是指针,而不是指向的内存(调用&中有多余的fread

推荐阅读