【问题标题】:Why does my program not read binary files properly?为什么我的程序无法正确读取二进制文件?
【发布时间】:2020-07-31 19:31:45
【问题描述】:

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

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++ file binary binaryfiles


【解决方案1】:
Challenge* newChallenge;
while (!file.eof())
{
    file.read((char*)&newChallenge, sizeof(Challenge));
...

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

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

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

【讨论】:

  • 好吧,所以你说我删除了 &,使挑战* newChallenge = new Challenge; ?
  • @Stukata 这将解决第 1 点,但第 2 点仍会阻止您的程序工作。 对象不是字节块,通常你不能通过读取字节来生成对象。
猜你喜欢
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 2019-09-24
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多