###### tags: `程設筆記` {%hackmd theme-dark %} # Chaper 8 Sequential-Access Files ## fstream * ofstream and ifstream is include in fstream * ofstream: creats and writes files * ifstream: reads from files ![](https://i.imgur.com/BXqxxcS.png) Ex1(Input data to txt): ```c++= #include <iostream> #include <string> #include <fstream> using namespace std; int main(){ fstream file; file.open("test.txt", ios::out); string name, birthday; if(!file){ cerr<<"File could not be open."<<endl; exit(1); //exit with error } cout<<"Input the name and birthday(input end-of-file to end the program):"; while(cin>>name>>birthday){ outClientFile<<name<<' '<<birthday<<"\n"; cout<<"Input the name and birthday(input end-of-file to end the program):"; } outClientFile.close(); } ``` Ex2(Read from txt): ```c++= #include <iostream> #include <string> #include <fstream> using namespace std; int main(){ fstream file("test.txt", ios::in); string name, birthday; if(!file){ cerr<<"The file cannot be opened."; exit(1); } while(file>>name>>birthday){ cout<<name<<" "<<birthday<<"\n"; } outClientFile.close(); } ``` * Reading from a specific line(seekg(), seekp()) Reference: http://c.biancheng.net/view/1541.html * name.seekg(0); => reposition the pointer to location 0. * To read a sequential file again, we need to add name.clear() before the seekg. ![](https://i.imgur.com/8Ourtup.png) ![](https://i.imgur.com/QbXSudS.png) * Telling you the current location(tellg(), tellp())