C++ file read/write as buffer size
ITWeb/개발일반 2013. 2. 1. 14:55file read and write as block size.
#include <iostream>
#include <fstream>
using namespace std;
const int32_t BUFFER_SIZE = 64;
int main () {
char* buff;
int32_t currSize = 0;
int32_t totalSize = 0;
int32_t extraSize = 0;
ifstream is;
ofstream os;
is.open ("plain.txt", ifstream::in);
os.open ("plain_bak.txt", ofstream::ate);
// get size of file:
is.seekg (0, ios::end);
totalSize = is.tellg();
is.seekg (0, ios::beg);
cout << "file size : " << totalSize << endl;
// allocate memory:
buff = new char[BUFFER_SIZE];
while ( !is.eof() ) {
extraSize = totalSize - currSize;
if ( extraSize >= BUFFER_SIZE ) {
memset(buff, 0x00, BUFFER_SIZE);
is.read(buff, BUFFER_SIZE);
os.write(buff, BUFFER_SIZE);
} else {
memset(buff, 0x00, BUFFER_SIZE);
is.read(buff, extraSize);
os.write(buff, extraSize);
}
currSize = currSize + BUFFER_SIZE;
}
is.close();
os.close();
delete[] buff;
return 0;
}