파일의 임의 위치 접근하기
파일입출력을 하다보면 파일의 임의 위치에 있는 값들을 받거나 쓰고 싶을 수있다. 이때 사용하는 방법이다.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const string filename = "my_file.txt";
//make a file
{
ofstream ofs(filename);
for (char i = 'a'; i <= 'z'; i++)
ofs << i;
ofs << endl;
}
//read a file
{
ifstream ifs(filename);
//처음에서 5바이트 이후에 값을 받아들이기
//cplusplus 참조
ifs.seekg(5);
cout << (char)ifs.get() << endl;
ifs.seekg(5, ios::cur);
cout << (char)ifs.get() << endl;
//현재 위치 알려줌
cout << ifs.tellg() << endl;
//남은 ifs의 값들을 str에 넣기
string str;
getline(ifs, str);
cout << str << endl;
}
{
fstream iofs(filename);
iofs.seekg(5);
iofs.put('A'); //write
}
return 0;
}
출력

참고
홍정모의 따라하며 배우는 c++