Lưu trữ dữ liệu trên tập tin
Nguyễn Minh Thành Thanhnm.itc@itc.edu.vn
Giới Thiệu
Tập tin văn bản: tập tin dùng để ghi các ký tự lên đĩa theo các dòng. Tập tin nhị phân: tập tin dùng để ghi các cấu trúc dạng nhị phân
(được mã hoá).
2
Thao tác với tập tin
Bước 1: Mở tập tin để đọc/ ghi. Bước 2: Các xử lý trên tập tin. Bước 3: Đóng tập tin.
3
Lớp fstream -
• Mở file
fstream::open()
• Đọc file
fstream::Operator >>
• Ghi dữ liệu vào file
fstream::Operator <<
• Đóng file
fstream::close()
4
Tạo tập tin văn bản
void main() {
fstream file(“d:\\file_text.txt”, ios::out); file<<“Write to file"; file.close();
}
5
Đọc toàn bộ tập tin văn bản
void main() {
char str[2000]; fstream file(“d:\\file_text.txt”, ios::in); while(file >> str) cout << str ;
file.close();
6
}
Đọc từng dòng tập tin văn bản
void main() {
char str[2000]; fstream file(“d:\\file_text”, ios::in); while(!file.eof()) {
file.getline(str,2000);
cout < }
file.close(); 7 } void main()
{ fstream file(“d:\\file.bin”, ios::out | ios::binary);
file.write(“Write to file“, ;
file.close(); } 8 void main()
{ char str[2000];
fstream file(“d:\\file.bin”, ios::in | ios::binary);
while(file.read(str)
cout << str ; file.close(); 9 } 10Tạo tập tin nhị phân
Đọc tập tin nhị phân
Bài tập ví dụ