Bài giảng Ngôn ngữ lập trình C++ - Ra vào dữ liệu trên File

thư viện iostream

có các header file với hàng trăm chức năng vào/ra

<iostream.h>

vào chuẩn – Standard input (cin)

ra chuẩn – Standard output (cout)

dòng báo lỗi không có bộ nhớ đệm – Unbuffered error (cerr)

dòng báo lỗi có dùng bộ nhớ đệm – Buffered error (clog)

<iomanip.h>

các stream manipulator (có tham số) để định dạng I/O

<fstream.h>

các thao tác xử lý file

 

 

 

ppt59 trang | Chuyên mục: C/C++ | Chia sẻ: dkS00TYs | Lượt xem: 5027 | Lượt tải: 1download
Tóm tắt nội dung Bài giảng Ngôn ngữ lập trình C++ - Ra vào dữ liệu trên File, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
// Create a sequential file. 3 #include ................... 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 11 #include 12 13 using std::ofstream; 14 15 #include // exit prototype 16 17 int main() 18 { 19 // ofstream constructor opens file 20 ofstream outClientFile( "clients.dat", ios::out ); 21 22 // exit program if unable to create file 23 if ( !outClientFile ) { // overloaded ! operator 24 cerr > account >> name >> balance ) { 38 outClientFile 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 using std::left; 11 using std::right; 12 using std::fixed; 13 using std::showpoint; 14 15 #include 16 17 using std::ifstream; 18 19 #include 20 21 using std::setw; 22 using std::setprecision; 23 24 #include // exit prototype 25 26 void outputLine( int, const char * const, double ); 27 fig14_08.cpp(2 of 3) 28 int main() 29 { 30 // ifstream constructor opens the file 31 ifstream inClientFile( "clients.dat", ios::in ); 32 33 // exit program if ifstream could not open file 34 if ( !inClientFile ) { 35 cerr > account >> name >> balance ) 49 outputLine( account, name, balance ); 50 51 return 0; // ifstream destructor closes the file 52 53 } // end main fig14_08.cpp(3 of 3)fig14_08.cppoutput (1 of 1) 54 55 // display single record from file 56 void outputLine( int account, const char * const name, 57 double balance ) 58 { 59 cout > dành cho dữ liệu định dạng outFile (&number), 	 sizeof( number ) ); &number là int * đổi thành const char * bằng reinterpret_cast sizeof(number) kích thước của number (một số int) tính theo byte tương tự đối với hàm read (more later) Chú ý: chỉ dùng write/read giữa các máy tương thích mở file kiểu ios::binary để đọc/ghi thô thường dùng để ghi toàn bộ một struct hoặc một đối tượng ra file 8.13.2 Ghi file truy nhập ngẫu nhiên Bài toán chương trình quản lý tài khoản Lưu trữ tối đa 100 bản ghi kích thước cố định Bản ghi Mã tài khoản - Account number (khóa) Họ và tên - First and last name Số tiền hiện có trong tài khoản - Balance Các thao tác: cập nhật, tạo mới, xóa, liệt kê tất cả các tài khoản ra một file Tiếp theo: chương trình tạo file chứa 100 bản ghi rỗng clientData.h(1 of 2) 1 // Fig. 14.10: clientData.h 2 // Class ClientData definition used in Fig. 14.12–Fig. 14.15. 3 #ifndef CLIENTDATA_H 4 #define CLIENTDATA_H 5 6 #include 7 8 using std::string; 9 10 class ClientData { 11 12 public: 13 14 // default ClientData constructor 15 ClientData( int = 0, string = "", string = "", double = 0.0 ); 16 17 // accessor functions for accountNumber 18 void setAccountNumber( int ); 19 int getAccountNumber() const; 20 21 // accessor functions for lastName 22 void setLastName( string ); 23 string getLastName() const; 24 clientData.h(2 of 2) 25 // accessor functions for firstName 26 void setFirstName( string ); 27 string getFirstName() const; 28 29 // accessor functions for balance 30 void setBalance( double ); 31 double getBalance() const; 32 33 private: 34 int accountNumber; 35 char lastName[ 15 ]; 36 char firstName[ 10 ]; 37 double balance; 38 39 }; // end class ClientData 40 41 #endif 8.13.3 Ghi dữ liệu vào vị trí tùy ý trong file truy nhập ngẫu nhiên Dùng seekp để ghi vào vị trí chính xác trong file Bản ghi đầu tiên bắt đầu từ đâu? Byte 0 Bản ghi thứ hai? Byte 0 + sizeof(object) Bản ghi bất kỳ? (Recordnum - 1) * sizeof(object) 8.13.4 Đọc tuần tự dữ liệu từ file truy nhập ngẫu nhiên read - tương tự write Đọc các byte thô từ file vào bộ nhớ inFile.read( reinterpret_cast( &number ), 	sizeof( int ) ); &number: địa chỉ để lưu dữ liệu sizeof(int): số byte cần đọc Không dùng inFile >> number cho dữ liệu thô - nhị phân >> nhận char * Chương trình tiếp theo lấy dữ liệu từ một file random-access duyệt tuần tự qua từng bản ghi If no data (accountNumber == 0) then skip fig14_14.cpp(1 of 2) 1 // Fig. 14.14: fig14_14.cpp 2 // Reading a random access file. ...... 25 #include "clientData.h" // ClientData class definition 26 27 void outputLine( ostream&, const ClientData & ); 28 29 int main() 30 { 31 ifstream inCredit( "credit.dat", ios::in ); 32 33 // exit program if ifstream cannot open file 34 if ( !inCredit ) { 35 cerr ( &client ), 48 sizeof( ClientData ) ); fig14_14.cpp(2 of 2) 50 // read all records from file 51 while ( inCredit && !inCredit.eof() ) { 52 53 // display record 54 if ( client.getAccountNumber() != 0 ) 55 outputLine( cout, client ); 56 57 // read next from file 58 inCredit.read( reinterpret_cast( &client ), 59 sizeof( ClientData ) ); 60 61 } // end while 62 63 return 0; 64 65 } // end main 66 67 // display single record 68 void outputLine( ostream &output, const ClientData &record ) 69 { 70 output 6 7 using std::cout; ... 15 using std::showpoint; 16 17 #include 18 19 using std::ofstream; 20 using std::ostream; 21 using std::fstream; 22 23 #include 24 25 using std::setw; 26 using std::setprecision; 27 28 #include // exit prototype 29 #include "clientData.h" // ClientData class definition fig14_15.cpp(2 of 14) 30 31 int enterChoice(); 32 void printRecord( fstream& ); 33 void updateRecord( fstream& ); 34 void newRecord( fstream& ); 35 void deleteRecord( fstream& ); 36 void outputLine( ostream&, const ClientData & ); 37 int getAccount( const char * const ); 38 39 enum Choices { PRINT = 1, UPDATE, NEW, DELETE, END }; 40 41 int main() 42 { 43 // open file for reading and writing 44 fstream inOutCredit( "credit.dat", ios::in | ios::out ); 45 46 // exit program if fstream cannot open file 47 if ( !inOutCredit ) { 48 cerr > menuChoice; // receive choice from user 109 110 return menuChoice; 111 112 } // end function enterChoice 113 114 // create formatted text file for printing 115 void printRecord( fstream &readFromFile ) 116 { 117 // create text file 118 ofstream outPrintFile( "print.txt", ios::out ); 119 120 // exit program if ofstream cannot create file 121 if ( !outPrintFile ) { 122 cerr ( &client ), 137 sizeof( ClientData ) ); 138 139 // copy all records from record file into text file 140 while ( !readFromFile.eof() ) { 141 142 // write single record to text file 143 if ( client.getAccountNumber() != 0 ) 144 outputLine( outPrintFile, client ); 145 146 // read next record from record file 147 readFromFile.read( reinterpret_cast( &client ), 148 sizeof( ClientData ) ); 149 150 } // end while 151 152 } // end function printRecord 153 fig14_15.cpp(8 of 14) 154 // update balance in record 155 void updateRecord( fstream &updateFile ) 156 { 157 // obtain number of account to update 158 int accountNumber = getAccount( "Enter account to update" ); 159 160 // move file-position pointer to correct record in file 161 updateFile.seekg( 162 ( accountNumber - 1 ) * sizeof( ClientData ) ); 163 164 // read first record from file 165 ClientData client; 166 updateFile.read( reinterpret_cast( &client ), 167 sizeof( ClientData ) ); 168 169 // update record 170 if ( client.getAccountNumber() != 0 ) { 171 outputLine( cout, client ); 172 173 // request user to specify transaction 174 cout > transaction; fig14_15.cpp(9 of 14) 177 178 // update record balance 179 double oldBalance = client.getBalance(); 180 client.setBalance( oldBalance + transaction ); 181 outputLine( cout, client ); 182 183 // move file-position pointer to correct record in file 184 updateFile.seekp( 185 ( accountNumber - 1 ) * sizeof( ClientData ) ); 186 187 // write updated record over old record in file 188 updateFile.write( 189 reinterpret_cast( &client ), 190 sizeof( ClientData ) ); 191 192 } // end if 193 194 // display error if account does not exist 195 else 196 cerr ( &client ), 214 sizeof( ClientData ) ); 215 216 // create record, if record does not previously exist 217 if ( client.getAccountNumber() == 0 ) { 218 219 char lastName[ 15 ]; 220 char firstName[ 10 ]; 221 double balance; fig14_15.cpp(11 of 14) 222 223 // user enters last name, first name and balance 224 cout > setw( 15 ) >> lastName; 226 cin >> setw( 10 ) >> firstName; 227 cin >> balance; 228 229 // use values to populate account values 230 client.setLastName( lastName ); 231 client.setFirstName( firstName ); 232 client.setBalance( balance ); 233 client.setAccountNumber( accountNumber ); 234 235 // move file-position pointer to correct record in file 236 insertInFile.seekp( ( accountNumber - 1 ) * 237 sizeof( ClientData ) ); 238 239 // insert record in file 240 insertInFile.write( 241 reinterpret_cast( &client ), 242 sizeof( ClientData ) ); 243 244 } // end if 245 fig14_15.cpp(12 of 14) 246 // display error if account previously exists 247 else 248 cerr ( &client ), 266 sizeof( ClientData ) ); 267 fig14_15.cpp(13 of 14) 268 // delete record, if record exists in file 269 if ( client.getAccountNumber() != 0 ) { 270 ClientData blankClient; 271 272 // move file-position pointer to correct record in file 273 deleteFromFile.seekp( ( accountNumber - 1 ) * 274 sizeof( ClientData ) ); 275 276 // replace existing record with blank record 277 deleteFromFile.write( 278 reinterpret_cast( &blankClient ), 279 sizeof( ClientData ) ); 280 281 cout > accountNumber; 311 312 } while ( accountNumber 100 ); 313 314 return accountNumber; 315 316 } // end function getAccount Kỹ năng File có định dạng (text) File binary ofstream ifstream fstream Truy cập tuần tự Truy cập ngẫu nhiên Bài luyện tập Bài 1: Mở file text ghi các số từ 0 đến 9 Mở file text đọc các số từ 0 đến 9 Mở file binary cho 2 câu trên Bài 2: Đọc, ghi một cấu trúc từ file định dạng Đọc, ghi một cấu trúc từ file Bài 3: Sắp xếp trên file Tìm kiếm nhị phân trên file Bài 4: Cho cấu trúc sinh viên, làm việc với file text và file nhị phân Thực hiện các chức năng: Đọc dữ liệu từ file, ghi dữ liệu từ file Lọc thông tin theo ràng buộc Update sinh viên Chèn sinh viên Xóa sinh viên Bài luyện tập Bài 1 Hàm tính độ lớn của file Xây dựng hàm copy file Xây dựng hàm xóa file Xây dựng hàm cắt file, hàm kết hợp file Bài 2 Xây dựng file từ điển Cập nhật thông tin: chèn, sửa, xóa, sắp xếp Tìm kiếm 

File đính kèm:

  • pptBài giảng Ngôn ngữ lập trình C++ - Ra vào dữ liệu trên File.ppt