生成二进制文件并修改部分内容

1 typedef struct Point
2 {
3     double latitude;
4     double longtitude;
5     int height;
6 }PointXYZ;
View Code

声明一个point结构体。

 1 while(getline(……))
 2     {
 3         ss.clear();
 4         ss.str(buffer);
 5         //char *strtok(char *str, const char *delim);
 6         p=const_cast<char*>(buffer.c_str());
 7         arr=strtok(p,delim);
 8         //分割该行并做简单处理写入二进制文件outfile
 9         while(arr)
10         {
11             y_longtitude=computeLongtitude(colsIndex);
12             x_latitude=computeLatitude(rowIndex);
13             height=atoi(arr);
14             point.latitude=x_latitude;
15             point.longtitude=y_longtitude;
16             point.height=height;
17             //outfile<<setiosflags(ios::fixed) << setprecision(7)<<x_latitude<<" "<<y_longtitude<<" "<<arr<<endl;
18             outfile.write((char*)(&point),sizeof(PointXYZ));
19             arr=strtok(NULL,delim);//循环处理
20             colsIndex++;
21         }
22         //输出 处理的提示信息
23         //cout<<(cntIndex++)<<"行已处理!********"<<endl;
24         Sleep(20);//
25         //cin>>z;
26         rowIndex++;
27     }
View Code

上面主要是,如何分割读入的一行内容(高程值用空格来分割),char *strtok(char *str, const char *delim);如何遍历分割后的内容,将str指针置为NULL就可以了。

 1 for(int i=0;i<rowNumber*colsNumber&&!outfile.eof();i++)
 2     {
 3         ios::pos_type currPos=outfile.cur;//保存当前文件指针位置
 4         PointXYZ tempPoint;
 5         outfile.read((char*)(&tempPoint),sizeof(PointXYZ));
 6         tempPoint.latitude=0;
 7         outfile.seekp(i*sizeof(PointXYZ),ios::beg);//文件指针跳至第 i个结构体位置
 8         outfile.write((char*)(&tempPoint),sizeof(PointXYZ));
 9         
10         cout<<setiosflags(ios::fixed) << setprecision(7)<<tempPoint.latitude<<" "<<tempPoint.longtitude<<" "<<tempPoint.height<<endl;
11         Sleep(200);
12         outfile.seekp(sizeof(PointXYZ),currPos);//根据currPos开始下一个struct对象
13     }

高程值数量:rowNumber*colsNumber。比如要修改高程值,保存当前指针,然后指向下一个struct位置,继续修改,然后并保存……重复。一定要搞清楚,修改的是哪个struct(seekp(i*sizeof(PointXYZ),ios::beg)),write写回或者覆盖旧struct,然后继续下一个struct修改操作。

原文地址:https://www.cnblogs.com/DebugMe/p/3167012.html