반응형
안녕하세요. 훈츠입니다. 금일은 파일 입출력 사용 방법에 대해 좀더 내용을 추가해서 포스팅 합니다.
파일 쓰기
다음 세가지 방식으로 쓸수 있습니다.
-
쓰기 기본 연산자 : <<
-
put() : 한물자 쓰기, 공백문자 까지 포함하여 쓰기.
-
write() : binary 파일 쓰기 , 이와 같은 형태로 씀((char*) & 쓸데이터, sizeof(쓸 데이터타입))
파일 읽기
다음 세가지 방식으로 쓸수 있습니다.
-
읽기 기본 연산자 : >>
-
get() : 한문자 읽기, 공백문자 까지 포함하여 읽음.
-
read() : binary 파일 읽기, 이와 같은 형태로 씀((char*) & 쓸데이터, sizeof(쓸 데이터타입))
바이너리 코드로 저장 방법 및 불러오기
바이너리 코드로 저장 및 불러올때는 ios::binary, 와 write() 함수와 read() 함수를 통해서 저장 및 로드 할수있습니다.
-
다음 ios::in | ios::binary 같은 형태로 결합 합니다.
-
바이너리 : 사용자가 지정한 단위로 저장 및 열기
-
텍스트 : 1byte 단위로 저장 및 열기
예제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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
using namespace std;
struct DATE
{
int year;
int monthe;
int day;
};
int main()
{
DATE sDate = { 2020, 5, 9 };
ofstream OutFile;
cout << "'t' 는 자동 text 모드 입력" << endl;
cout << "'b' 는 자동 바이너리 모드 입력" << endl;
cout << "'a' 는 자동 text 모드 입력" << endl;
cout << "모드를 입력 하세요. t,b,a"<< endl;
char writeMode;
char ch;
cin >> writeMode;
if (writeMode == 't') {
OutFile.open("test.txt", ios::out);
OutFile << sDate.year << " " << sDate.monthe << " " << sDate.day << endl;
}
if (writeMode == 'b') {
OutFile.open("test.txt", ios::out | ios::binary);
OutFile.write((char*)&sDate, sizeof(DATE));
}
if (writeMode == 'a') {
OutFile.open("test.txt", ios::out );
while (cin.get(ch)) {
if (ch == 'q')
break;
OutFile.put(ch); //OutFile << ch 동일 구문입니다.
}
}
OutFile.close();
// 파일 읽어오기 't' text 읽어오기, 'b' 바이너리 읽어오기
cout << "읽기 모드를 입력 하세요. t,b" << endl;
char readMode;
cin >> readMode;
if (readMode == 't') {
cout << "text" << endl;
ifstream iMyFile("test.txt", ios::in);
while (iMyFile.get(ch)) {
cout << ch;
}
cout << endl;
iMyFile.close();
}
else if(readMode == 'b') {
cout << "binary"<<endl;
ifstream MyFile("test.txt", ios::in | ios::binary);
MyFile.read((char*)&sDate, sizeof(DATE));
cout<< sDate.year << " " << sDate.monthe << " " << sDate.day << endl;
MyFile.close();
}
return 0;
}
|
cs |
다음 test text 에 저장된 binary code 인 ? | 데이터를 binary 로 읽었을때 다음과 같이 2020 5 9일 이라는 것으로 나오는 부분을 확인 할수 있습니다.