Làm việc với tệp
Trang 1LẬP TRÌNH C++
§12 Làm việc với tệp
Trang 2I Các lệnh làm việc với tệp
ten_bien_tep.open(“ten_tep”,ios::mode);
Trang 3 ios::app : mở tệp để thêm vào cuối
đã có thì dữ liệu sẽ bị xóa
dữ liệu sẽ bị xóa
inFile.eof() = true nếu cuối tệp
Trang 4II Bài tập :
1 Nhập dữ liệu vào tệp :
2 Đọc tệp và in ra màn hình
Trang 5#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
outFile.open("sale.dat",ios::out);
if (outFile.is_open())
cout<<"Name (X to stop): "; getline(cin,name);
while (name!="X" && name!="x")
cin.ignore(1);
outFile<<name<<'#'<<sales<<endl;
cout<<"Name (X to stop): "; getline(cin,name); } outFile.close();}
Trang 6#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
inFile.open("sale.dat",ios::in);
if (inFile.is_open())
getline(inFile,name,'#');
while (!inFile.eof())
inFile.ignore(1);
cout<<name<<'#'<<sales<<endl;
inFile.close(); }
else cout<<"File could not be opened."<<endl;