我正在尝试做一个相当简单的任务,但对 FILE* 的工作方式感到困惑。所以我正在编写一个二进制文件(las 文件),它有一个标题,然后是二进制格式的点。由于这是一个巨大的文件,我正在逐步完成它。但是当文件指针正确写入几乎 3/4 的文件然后给出完全错误的文件位置指针时,问题就出现了。
//struct points written to
struct las_points{
float x;
float y;
float z;
float time;
};
int writepoints(){
outfilename = "pointcloud_13.las";
fout = fopen(outfilename,"wb+");
// numPts - total number of points to be processed
// numRec - number of records processed every time
numRec = numPts/4;
las_points *lp;
// ending size of the file
int endSize = 0,j=0;
// header is written
// endSize = 233
for(i=0;i<numPts;i+=numRec){
lp = (las_points*)malloc(sizeof(las_points)*numRec);
// some processing done
printf("Iteration - %d\n",j);
lasWritePoints(lp,fout,numRec,endSize);
fflush(fout);
free(lp);
lp = NULL;
}
fclose(fout);
}
int lasWritePoints(las_points*lp, FILE* fout,int numRec,int &endSize){
if(!fout || !lp){
printf("File couldnt be written \n");
exit(1);
}
printf("endSize - %d \n",endSize);
fseek(fout,endSize,SEEK_SET);
for(int i=0;i<numRec;i++) {
fwrite(&lp[i].x,sizeof(float),1,fout);
fwrite(&lp[i].y,sizeof(float),1,fout);
fwrite(&lp[i].z,sizeof(float),1,fout);
fseek(fout,8,SEEK_CUR);
fwrite(&lp[i].time,sizeof(float),1,fout);
}
endSize = ftell(fout);
printf("endSize - %d \n",endSize);
}
仅复制二进制文件的写入。问题是对于文件的前四次迭代,它运行平稳。然后在最后一次迭代结束时,它给出的 endSize 小于开始的 endSize。
Output:
Total size of file to be read: 1258456752
Iteration : 0
endSize : 233
endSize : 550575041
Iteration : 1
endSize : 550575041
endSize : 1101149849
Iteration : 2
endSize : 1101149849
endSize : 1651724657
Iteration : 3
endSize : 1651724657
endSize : 54815783
有人可以指出我做错了什么吗?