안녕하세요. 훈츠입니다. 금일은 파일 탐색 방법인 seekg, seekp 에 대해 설명 드리겠습니다.
파일 탐색
파일 포인터의 위치를 원하는 방향으로 이동시켜 내용을 읽거나 쓰고자 할때 이용 합니다.
-
Ios::beg 파일의 시작 (begin 을 나타냅니다.)
-
Ios::cur 파일의 현재 위치 (current 를 나타냅니다.)
-
Ios::end 파일의 끝 (end 종료지점을 나타냅니다.)
C 언어의 fseek() 함수와 동일 합니다.
다음 C언어의 포스팅을 참조 해보시면 이해 하시는데 도움이 됩니다.
https://rain2002kr.tistory.com/159?category=382972
[C] C언어 9일차 파일 입출력
안녕하세요. 훈츠 입니다. 금일은 파일 입출력에 대해 알아보도록 하겠습니다. C, C++ 동일하게 사용된다고 하니 이번기회에 잘 정리해 놓으면 편할듯 싶네요. 파일 입출력 종류 공통점 : 0과 1로 저장된 이진 데..
rain2002kr.tistory.com
Istream 읽기 용 포인터 탐색 : seekg 함수 사용
istream 을 사용 할 시에는, seekg 함수를 이용합니다.
basic_istream<Elem. Tr> & seekg ( pos_type pos );
- seekg ( 0 ) ; //커서 포지션 위치 지정
basic_istream<Elem. Tr> & seekg ( off_type off, ios_base::seekdir way
- seekg ( sizeof(Date) * 2 , ios::beg ) ; //첫번째 매개 변수 포인터 이동후, 현재 지점부터 읽기
ios::beg, ios::cur, ios::end
ostream 쓰기 용 포인터 탐색 : seekp 함수 사용
ostream 을 사용 할 시에는, seekp 함수를 이용합니다.
basic_istream<Elem. Tr> & seekp ( pos_type pos );
- seekp ( 0 ) ; //커서 포지션 위치 지정
basic_istream<Elem. Tr> & seekp ( off_type off, ios_base::seekdir way
- seekp ( sizeof(Date) * 2 , ios::beg ) ; //첫번째 매개 변수 포인터 이동후, 현재 지점부터 읽기
Ios::beg, ios::cur, ios::end
예제1 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
//Hoons Blog---https://rain2002kr.tistory.com-----------------------------------------------코드///
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
using namespace std;
struct DATE
{
int year;
int month;
int day;
};
int main()
{
DATE sDate[3] = { { 2020, 5, 9 },{ 2020, 5, 10 },{ 2020, 5, 11 } };
DATE Date;
DATE wDate = { 0,1,2 };
ofstream OutFile;
OutFile.open("test.txt", ios::out | ios::binary);
OutFile.write((char*)sDate, sizeof(DATE) * 3);
OutFile.seekp(0); //커서 이동
OutFile.write((char*)&wDate, sizeof(DATE)); //(값을 전달해줄매개변수, 갯수 )
OutFile.close();
ifstream InputFile;
memset(sDate, 0, sizeof(DATE) * 3); // 0 으로 초기화
InputFile.open("test.txt", ios::in | ios::binary);
InputFile.read((char*)sDate, sizeof(DATE) * 3);
for (int i = 0; i < 3; i++) {
cout << sDate[i].year << " " << sDate[i].month << " " << sDate[i].day << endl;
}
cout << "임의의 파일 포인터에서 파일 읽기" << endl;
InputFile.seekg(sizeof(Date) * 1, ios::beg); // 포인터 옮기기
InputFile.read((char*)&Date, sizeof(DATE));
cout << Date.year << " " << Date.month << " " << Date.day << endl;
InputFile.close();
return 0;
}
|
cs |
'컴퓨터 언어 > C++' 카테고리의 다른 글
[C++] C++ 26일차 파일 입출력1 (0) | 2020.05.05 |
---|---|
[C++] C++ 25일차 STL 스탠다드 탬플리트 라이브러리 (0) | 2020.05.04 |
[C++] C++ 24일차 Template 3 클래스 객체 활용 (0) | 2020.05.01 |
[C++] C++ 21일차 friend 변수와 friend 클래스 (0) | 2020.04.25 |
[C++] C++ 20일차 static(정적) 멤버변수와 static(정적) 함수 (0) | 2020.04.24 |