我试图简单地将浮点值数组写入文件,然后将其读回。
我曾尝试直接从数组中写入它,但是当读回它时,我遇到了长度大于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;
谢谢,
戴夫
最佳答案
FILE* file = fopen (fileName, "wb");
FILE* file = fopen (fileName, "rb");