gpt4 book ai didi

c++ - 为什么 fwrite/fread 不像 56.806201550387598?

转载 作者:行者123 更新时间:2023-12-01 14:39:24 25 4
gpt4 key购买 nike

我正在尝试将结构保存到文件中,然后在另一个程序中再次读取它。我以前从未遇到过此问题,但至少据我所知,我从未尝试将值为 56.806201550387598 的双变量写入文件。并不是说我不知道​​为什么这个数字会产生任何问题,但是每当我尝试将包含该值的结构写入文件时,该字段以及在它之后声明的任何字段都只能从该结构中读出初始化值声明。

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

typedef struct statsSet{
int pathCount = 0;
double vMinMean = 0;
int imgsFound = 0;
int minWidth = INT_MAX;
int maxWidth = 0;
}statsSet;

void wrightToFile(statsSet sSet){
FILE* of = fopen ("imgStats2.dat", "w");
fwrite (&sSet, sizeof(statsSet), 1, of);
fclose (of);
}
statsSet readFromFile(){
statsSet statReadIn;
FILE *ifl = fopen ("imgStats2.dat" , "r");
fread(&statReadIn, sizeof(statsSet), 1, ifl);
fclose (ifl);
return statReadIn;
}
void pr(statsSet statReadIn){
cout << "pathCount: " << statReadIn.pathCount << "\n";
cout << "vMinMean: " << statReadIn.vMinMean<< "\n";
cout << "imgsFound: " << statReadIn.imgsFound<< "\n";
cout << "minWidth: " << statReadIn.minWidth<< "\n";
cout << "maxWidth: " << statReadIn.maxWidth<< "\n";
cout << "--------\n";
}

int main( int argc, char** argv ){
statsSet statTest;
statsSet statReadIn;

statTest.pathCount = 129;
statTest.imgsFound = 129;
statTest.minWidth = 488;
statTest.maxWidth = 501;

statTest.vMinMean = 56.806201550387591; // OK
wrightToFile(statTest);
statReadIn = readFromFile();
pr(statReadIn);


statTest.vMinMean = 56.806201550387598; //breaks
wrightToFile(statTest);
statReadIn = readFromFile();
pr(statReadIn);


statTest.vMinMean = 56.806201550387605; // OK
wrightToFile(statTest);
statReadIn = readFromFile();
pr(statReadIn);
}

输出:

pathCount: 129
vMinMean: 56.8062
imgsFound: 129
minWidth: 488
maxWidth: 501
--------
pathCount: 129
vMinMean: 0
imgsFound: 0
minWidth: 2147483647
maxWidth: 0
--------
pathCount: 129
vMinMean: 56.8062
imgsFound: 129
minWidth: 488
maxWidth: 501
--------

我做错了什么?

我使用的是 Windows 10、Visual Studio Code 和 MinGW-w64。

最佳答案

使用写入二进制模式。文本模式对于二进制数据来说是非常随机的。

FILE* of = fopen ("imgStats2.dat", "wb"); 

FILE *ifl = fopen ("imgStats2.dat" , "rb");

关于c++ - 为什么 fwrite/fread 不像 56.806201550387598?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61828086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com