c++ fstream用法(2)
一>
1 #include "stdafx.h" 2 #include<iostream> 3 #include<string> 4 #include<fstream> 5 using namespace std; 6 7 class Rectangle 8 { 9 private: 10 double length, width; 11 public: 12 Rectangle(double l, double w); 13 }; 14 15 16 Rectangle::Rectangle(double l, double w) :length(l), width(w) 17 {} 18 19 int main() 20 { 21 Rectangle rect(20.0, 10.3); 22 ofstream out("a.dat", ios_base::binary); //文件的输出 23 if (out.is_open()) //如果打开成功 24 { 25 out.write((char*)&rect, sizeof(Rectangle));//把Rectangle类的rect成员写入 26 out.close(); //注意:此步一定不能省 27 } 28 char* buf = new char[sizeof(Rectangle)]; //缓冲区 29 ifstream in("a.dat", ios_base::binary); //文件的写入 30 if (in.is_open()) //如果文件打开成功 31 { 32 in.read(buf, sizeof(Rectangle)); //从in指定的已打开文件中读取Rectangle字节到buf中 33 in.close(); //注意:此步一定不能省 34 } 35 return 0; 36 }
结果(注意:.dat文件要用WinHex打开,网上有下载):
二>
1 #include "stdafx.h" 2 #include<iostream> 3 #include<string> 4 #include<fstream> 5 using namespace std; 6 7 class Rectangle 8 { 9 private: 10 double length, width; 11 public: 12 Rectangle(double l, double w); 13 void displayArea() { cout << length * width << endl; } 14 }; 15 16 17 Rectangle::Rectangle(double l, double w) :length(l), width(w) 18 {} 19 20 int main() 21 { 22 int a[] = { 6,8,2,1 }; 23 Rectangle rect(20.0, 10.3); 24 ofstream out("a.dat", ios_base::binary); 25 if (out.is_open()) 26 { 27 out.write((char*)&rect, sizeof(Rectangle)); 28 out.write((char*)a, 4 * sizeof(int)); //对数组来说,数组有n个元素那么后面就是n*sizeof(int) 29 out.close(); 30 } 31 char* buf = new char[sizeof(Rectangle)]; 32 char* buf2 = new char[4 * sizeof(int)]; 33 ifstream in("a.dat", ios_base::binary); 34 if (in.is_open()) 35 { 36 in.read(buf, sizeof(Rectangle)); 37 in.read(buf2, sizeof(int) * 4); 38 int *a = new int[4]; 39 memcpy(a, buf2, 4 * sizeof(int)); 40 cout << a[3] << endl; 41 delete[] a; 42 in.close(); 43 44 Rectangle* pr = (Rectangle*)buf; 45 pr->displayArea(); 46 } 47 delete[] buf; 48 return 0; 49 }
结果:
三>
1 #include "stdafx.h" 2 #include<iostream> 3 #include<string> 4 #include<fstream> 5 using namespace std; 6 7 class Rectangle 8 { 9 private: 10 double length, width; 11 public: 12 Rectangle(double l, double w); 13 void displayArea() { cout << length * width << endl; } 14 }; 15 16 17 Rectangle::Rectangle(double l, double w) :length(l), width(w) 18 {} 19 20 int main() 21 { 22 fstream file("a.txt", ios_base::out | ios_base::app); 23 if (file.is_open()) 24 { 25 file << "Hello world!"; 26 file.close(); 27 28 } 29 file.open("a.txt", ios_base::in); 30 if (file.is_open()) 31 { 32 while (file.good()) 33 { 34 string words; 35 file >> words; 36 cout << words << " "; 37 } 38 file.close(); 39 cout << endl; 40 } 41 return 0; 42 }
结果:(文件中与命令提示框输出得一样哦)