標籤:c++ 檔案操作
/*一、資料的層次:位 位元組 域/記錄二、循序檔:將所有的記錄順序輸入檔案。一個有限字元構成的順序字元流。三、C++標準庫中:ifstream(檔案讀取) ofstream(檔案寫入) fstream(檔案讀取寫入)四、使用/建立檔案的基本流程:1. 開啟檔案 2.讀/寫檔案 3.關閉檔案五、建立循序檔#include <fstream>ofstream outFile("clients.dat",ios::out|ios::binary);ios::out 輸出到檔案,刪除原有內容ios::app 輸出到檔案,保留原有內容,總是在尾部添加ios::binary 以二進位檔案格式開啟檔案ofstream fout;fout.open("test.out",ios::out|ios::binary);if(!fout){cerr<<"File open error!"<<endl;}六、檔案的讀寫指標(標識檔案操作的當前位置,指標在哪裡,讀寫操作就在哪裡進行)對於輸入檔案,有一個讀指標對於輸出檔案,有一個寫指標對於輸入輸出檔案,有一個讀寫指標ofstream fout("a1.out",ios::app);long location = fout.tellp();location = 10L;fout.seekp(location);fout.seekp(location,ios::beg); //從頭數locationfout.seekp(location,ios::cur); //從當前位置數locationfout.seekp(location,ios::end); //從尾部數location,location可以是負值ifstream fin("a1.in",ios::in);long location = fin.tellg();location = 10L;fout.seekg(location);fout.seekg(location,ios::beg); //從頭數locationfout.seekg(location,ios::cur); //從當前位置數locationfout.seekg(location,ios::end); //從尾部數location,location可以是負值七、二進位檔案讀寫int x = 10;fout.seekp(20,ios::beg);fout.write((const char*)(&x),sizeof(int));fin.seekg(0,ios::beg);fin.read((char *)(&x),sizeof(int));二進位檔案讀寫,直接寫位元據,記事本看未必正確顯示關閉檔案.close()*/#pragma warning(disable:4996)#include <iostream>#include <fstream>#include <cstring>using namespace std;class CStudent{public:char szName[20];int nScore;};////int main()//{//CStudent s;//ofstream OutFile("StuScores.dat", ios::out | ios::binary);//while (cin >> s.szName >> s.nScore){//if (stricmp(s.szName, "exit") == 0)//break;//OutFile.write((char*) &s, sizeof(s));//}//OutFile.close();//return 0;//}//////int main()//{//CStudent s;//ifstream inFile("StuScores.dat", ios::in | ios::binary);//if (!inFile){//cout << "error" << endl;//return 0;//}//while (inFile.read((char*) &s, sizeof(s))){//cout << s.szName << " " << s.nScore << endl;//}//inFile.close();//return 0;//}//int main(){CStudent s;fstream iofile("StuScores.dat", ios::in | ios::out | ios::binary);if (!iofile){cout << "error" << endl;return 0;}iofile.seekp(2 * sizeof(s), ios::beg);iofile.write("Mike", strlen("Mike") + 1);iofile.seekg(0, ios::beg);while (iofile.read((char*) &s, sizeof(s)))cout << s.szName << " " << s.nScore << endl;iofile.close();return 0;}
C++檔案操作(一)