ProgrammingLang/c++
[C++ 개발자되기] 8. binary file read 및 write
jinkwon.kim
2019. 9. 9. 22:05
728x90
반응형
1. 목적
binary 및 text 파일을 읽기 및 쓰기 입니다. 파일 복사 및 암호화 파일 읽을때 유용합니다.
2. 필요 헤더
#include <fstream>
2. 사용함수
1) Read 함수
(1) 함수 명 : ifstream
(2) 핵심 옵션 : ifstream 핵심 옵션 std::ifstream::binary
(3) 함수 선언 : explicit basic_ifstream( const char* filename, std::ios_base::openmode mode = ios_base::in );
(4) 참조 : https://en.cppreference.com/w/cpp/io/basic_ifstream
2) write 함수
(1) 함수 명 : ofstream
(2) 핵심 옵션 : std::ios::out | std::ios::binary
(3) 함수 선언 : explicit basic_ofstream( const char* filename, std::ios_base::openmode mode = ios_base::out );
(4) 참조 : https://en.cppreference.com/w/cpp/io/basic_ofstream
3. Read Code
동적으로 메모리 할당 후 파일 읽기, 추가 팁 buffer의 할당은 unsigned char로 하시는게 정신 건강에 좋습니다. 암호화 파일을 읽으실 때 값이 깨질수 있습니다.
bool ReadFile(std::string filePath, unsigned char **_data, int *datalen)
{
std::ifstream is(filePath, std::ifstream::binary);
if (is) {
// seekg를 이용한 파일 크기 추출
is.seekg(0, is.end);
int length = (int)is.tellg();
is.seekg(0, is.beg);
// malloc으로 메모리 할당
unsigned char * buffer = (unsigned char*)malloc(length);
// read data as a block:
is.read((char*)buffer, length);
is.close();
*_data = buffer;
*datalen = length;
}
return true;
}
4. Write Code
파일에 binary data 쓰기
int WriteToFile(std::string filePath, unsigned char* data, MC_UINT data_len)
{
std::ofstream fout;
fout.open(filePath, std::ios::out | std::ios::binary);
if (fout.is_open()){
fout.write((const char*)data, data_len);
fout.close();
}
return 0;
}
728x90
반응형