//--------------------读写文件,结构体为单位--------------- #include <iostream> #include <fstream> using namespace std; typedef struct { int num;// ---------the number of the point float x;// ---------the x coordinate of the point float y;// ---------the y coordinate of the point }NODE ; typedef float REAL; void main() { char* nodefile ="node.txt"; //-------------write 5 nodes into a file --------------- //-------------define 5 nodes------------ NODE node[5]; REAL j=1.0; for (int i =0;i<5;i++) { node[i].num =i; node[i].x =j; node[i].y =j; j++; } //-------------write into file----------- ofstream outfile; outfile.open(nodefile,ios::out|ios::app); if (outfile.is_open()) { for (i =0;i<5;i++) { //outfile<<node[i]; //错误:---no operator defined which takes a right-hand operand of type 'NODE' (or there is no acceptable conversion) //---不能直接用 << operator 来写入结构体 outfile.write((char*)&node[i],sizeof(NODE)); } } else { cerr<<" the file write false "<<endl; } outfile.close();//=======================文件不关闭,后边直接打开,会出现数据不对,why?因为指针已经到了文件尾部?但文件不是有两个指针吗,一个读指针,一个写指针? //------------read and print contents of the file---------- ifstream infile; infile.open(nodefile,ios::in); NODE node_1; if (infile.is_open()) { for (i =0;i<5;i++) { //infile>>node_1;//--------wrong infile.read((char*)&node_1,sizeof(NODE)); cout<<" the node "<<i<<" :"<<endl; cout.fill('*');//---------format output cout.width(6);//---------format output cout<<node_1.num; cout.precision(6);//---------format output cout.width(6); cout<<node_1.x; cout.width(6); cout<<node_1.y; cout<<endl; } } else { cerr<<" the file read false "<<endl; } infile.close(); }