1. 程式人生 > >C++ 輸入輸出流之檔案操作和檔案流

C++ 輸入輸出流之檔案操作和檔案流

  • 使用成員函式read和write讀取二進位制檔案
    • istream &read(char *buffer, int len);
    • ostream& write(constchar *buffer, int len)
    • 舉例:將一批資料存入磁碟檔案
      • student stu[2] = {{"Li", 1001, 18}, {"Wang", 1002, 19}};
      • ofstream outfile("stu.dat", ios::binary);
      • if (!outfile)
      • {
      •     cerr << "open error" << endl;
      •     abort();
      • }
      • for (int i = 0; i < 2; i++)
      •     outfile.write((char *)&stu[i],sizeof(stu[i]));  // 取stu[i]的首地址,並強制轉換為(char *)
      • outfile.close();
    • 舉例:將一批資料從磁碟檔案中讀入記憶體
      • student stu[2];
      • ifstream infile("stu.dat", ios::binary);
      • if (!infile)
      • {
      •     cerr << "open error" << endl;
      •     abort();
      • }
      • for (int i = 0; i < 2; i++)
      •     infile.read((char *)&stu[i], sizeof(stu[i]));  // 一次讀入檔案中的全部資料
      • infile.close();
  • 與檔案指標有關的流成員函式
    • // g是輸入的標誌,p是輸出的標誌
    • gcount():   返回最後一次輸入所讀取的位元組數
    • tellg():    返回輸入檔案指標的當前位置
    • seekg(檔案中的位置):    將輸入檔案中指標移到指定的位置
    • seekg(位移量,參考位置):    以參照位置為基礎移動若干位元組
    • tellp():    返回輸出檔案指標當前的位置
    • seekp(檔案中的位置):    將輸出檔案中指標移到指定的位置
    • seep(位移量,參考位置):    一參考位置為基礎移動若干位元組
    • 函式引數中的"檔案中的位置"和"位移量"被指定為long型整數,以位元組為單位(例如100代表向前100位元組,-50代表向後50位元組)
    • "參考位置"為:
      • ios::beg: 檔案開頭    
      • ios::cur: 檔案當前位置    
      • ios::end: 檔案結尾
    • [備註]:對於fstream定義的變數,seekg和seekp操作的都是同一個指向檔案的指標
    • 修改檔案中的資料,再重新插入檔案中的位置採用的覆蓋方式。
    • 舉例:寫入二進位制檔案;然後讀出資料並修改,再寫入;最後輸出全部資料
    • #include <fstream>
      #include <iostream>
      #include <string>
      using namespace std;
      
      struct student
      {
      	string name;
      	int num;
      	short age;
      	char sex;
      };
      
      int main( )
      {
      	student stu[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
      	fstream iofile("stu.dat",ios::in|ios::out|ios::binary);
      	if(!iofile)
      	{
      		cerr<<"open error!"<<endl;
      		abort( );//退出程式
      	}
      	for(int i=0;i<3;i++)
      		iofile.write((char*)&stu[i],sizeof(stu[i]));
      
      	// 指向輸入檔案指標和輸出檔案指標一樣
      	cout << iofile.tellp() << endl;
      	cout << iofile.tellg() << endl;
      
      	student stud[3];
      	iofile.seekg(sizeof(stud[0]));  // 定位檔案指標位置
      
      	cout << iofile.tellp() << endl;
      	cout << iofile.tellg() << endl;
      
      	student temp;
      	iofile.read((char*)&temp, sizeof(temp));
      	temp.age = 22;
      	iofile.seekp(sizeof(temp));
      	iofile.write((char*)&temp, sizeof(temp));
      
      	iofile.seekg(0);  // 定位檔案指標位置為最開始,讀取所有元素
      	for(i=0;i<3;i++)
      		iofile.read((char*)&stud[i],sizeof(stud[i]));
      
      	iofile.close( );
      	for(i=0;i<3;i++)
      	{
      		cout<<"NO. "<<i+1<<endl;
      		cout <<"name: "<<stud[i].name <<endl;
      		cout<<"num: "<<stud[i].num<<endl;;
      		cout<<"age: "<<stud[i].age<<endl;
      		cout<<"sex: "<<stud[i].sex<<endl<<endl;
      	}
      	return 0;
      }