我试图简单地将一个浮点值数组写入文件然后再读回来 我曾尝试直接从数组中编写它,但是当读回它时,我一直为长度大于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;
谢谢, 戴夫
答案 0 :(得分:3)
FILE* file = fopen (fileName, "wb");
FILE* file = fopen (fileName, "rb");