본문 바로가기

Application-level프로그래밍

(C++) fstream 이용하기


MSDN을 참고했다.
(ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vcstdlib/html/0fd8591f-d0c0-4f25-8999-467d95ba2429.htm)

fstream s("filename", ios::in | ios::out); 과 같이 선언히여 읽기와 쓰기를 close() 없이 수행할 수 있다(ifstream 이나 ofstream 과는 다름).
멤버 함수 seekg()는  읽을 위치를 옮겨 주고, seekp()는 쓸 위치를 옮겨 준다. 인자는 byte 단위이므로 sizeof를 활용하자.
// basic_istream_seekg.cpp
// compile with: /EHsc
#include 
#include 

int main ( ) 
{
   using namespace std;
   ifstream file;
   char c, c1;

   file.open( "basic_istream_seekg.txt" );
   file.seekg(2);   // chars to skip
   file >> c;
   cout << c << endl;

   file.seekg( 0, ios_base::beg );
   file >> c;
   cout << c << endl;

   file.seekg( -1, ios_base::end );
   file >> c1;
   cout << c1 << endl;
}

 

basic_istream_seekg.txt
0123456789

출력
2
0
9