我试图简单地将浮点值数组写入文件,然后将其读回。
我曾尝试直接从数组中写入它,但是在读回它时,我一直遇到长度大于 153 的数组的问题。为了清楚起见,代码示例一个一个地写入每个浮点值。
对于索引大于或等于 153 的值,它们的值是 153.0,它们应该是 153.0, 154.0, 155.0, ...
为什么这段代码对我不起作用?
int length = 160;
char* fileName = "testFile.dat";
// Write data to file
FILE* file = fopen (fileName, "w");
for(int i = 0; i< length; i++){
// We are just storing the indices, so value at i is equal to i
float f = (float) i;
fwrite(&f, sizeof(float), 1, file);
}
fclose(file);
// Read data from file into results array
file = fopen(fileName, "r");
float* results = new float[length];
for(int i = 0; i< length; i++){
float f;
fread(&f, sizeof(float), 1, file);
results[i] = f;
}
fclose(file);
// Now check data in results array
bool fail = false;
for(int i = 0; i< length; i++){
if(results[i]!=(float)i){
fail = true; // This should not be hit, but it is!
}
}
delete [] results;
谢谢,戴夫