【发布时间】: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 类。
【问题讨论】:
-
您确定文件可以正确打开吗?你试过调试吗?请提供minimal reproducible example
-
文件确实打开正确,但是信息没有通过... sizeof(Challenge) = 4 正常吗?这对我来说有点离谱
-
我正在做的事情来自youtube.com/…
-
不确定我是否可以信任拼写错误的人的教程。
标签: c++ file binary binaryfiles