Sequential-Access Files-程式設計筆記

Shih Jiun Lin Lv4

Chaper 8 Sequential-Access Files

fstream

  • ofstream and ifstream is include in fstream
    • ofstream: creats and writes files
    • ifstream: reads from files

Ex1(Input data to txt):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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: link

  • name.seekg(0); => reposition the pointer to location 0.

  • To read a sequential file again, we need to add name.clear() before the seekg.

  • Telling you the current location(tellg(), tellp())

  • Title: Sequential-Access Files-程式設計筆記
  • Author: Shih Jiun Lin
  • Created at : 2023-01-17 23:00:50
  • Updated at : 2023-01-24 01:30:41
  • Link: https://shih-jiun-lin.github.io/2023/01/17/Chaper 8 Sequential-Access Files/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Sequential-Access Files-程式設計筆記