이진 입/출력을 테스트하는 비교적 간단한 프로그램을 테스트 중입니다. 기본적으로 헤더 (문자열)와 일부 데이터 (두 배)가있는 파일을 작성하고 있습니다. 코드는 다음과 같다 :C++의 이진 입출력
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
typedef std::ostream_iterator<double> oi_t;
typedef std::istream_iterator<double> ii_t;
std::ofstream ofs("data.bin", std::ios::in);
//-If file doesn't exist, create a new one now
if(!ofs) {
ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
}
else {
ofs.close();
ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
}
//-Write a header consisting of length of grid subdomain and its name
///*
const std::string grid = "Header";
unsigned int olen = grid.size();
ofs.write(reinterpret_cast<const char*>(&olen), sizeof(olen));
ofs.write(grid.c_str(), olen);
//*/
//-Now write the data
///*
std::vector<double> data_out;
//std::vector<std::pair<int, int> > cell_ids;
for(int i=0; i<100; ++i) {
data_out.push_back(5.0*double(i) + 100.0);
}
ofs << std::setprecision(4);
std::copy(data_out.begin(), data_out.end(), oi_t(ofs, " "));
//*/
ofs.close();
//-Now read the binary file; first header then data
std::ifstream ifs("data.bin", std::ios::binary);
///*
unsigned int ilen;
ifs.read(reinterpret_cast<char*>(&ilen), sizeof(ilen));
std::string header;
if(ilen > 0) {
char* buf = new char[ilen];
ifs.read(buf,ilen);
header.append(buf,ilen);
delete[] buf;
}
std::cout << "Read header: " << header << "\n";
//*/
///*
std::vector<double> data_in;
ii_t ii(ifs);
std::copy(ii, ii_t(), std::back_inserter(data_in));
std::cout << "Read data size: " << data_in.size() << "\n";
//*/
ifs.close();
//-Check the result
///*
for(int i=0; i < data_out.size(); ++i) {
std::cout << "Testing input/output element #" << i << " : "
<< data_out[i] << " " << data_in[i] << "\n";
}
std::cout << "Element sizes: " << data_out.size() << " " << data_in.size() <<
"\n";
//*/
return 0;
}
문제는 그 내가 작성하고 헤더와 실패 데이터 (I는 그 다음 데이터를 읽지 않습니다 확인을 모두 읽고 (다음 인쇄) 할 때, 헤더를 올바르게 표시합니다). 그러나 필자가 쓰기 섹션 (헤더 및/또는 데이터) 중 하나를 주석 처리 할 때 올바르게 읽힌 부분을 표시합니다. 나는 제대로 읽지 않을 것이라고 확신한다. 아마도 seekg의 사용법을 어딘가에서 놓치고있을 것입니다.
작품을 작동합니다. "Read header : Header \ n Read data size : 100 \ n"then 100 테스트 입출력 ... – Naddiseo
Visual Studio 2010을 사용하여 나를 위해 일합니다. – shengy
그건 이상합니다. 그것은 나를 위해 작동하지 않습니다. 코드는 그대로, 크기 0의 데이터를 읽는 인쇄물이므로 그 다음에 나오는 인쇄 섹션에서 구분됩니다. Cygwin 및 Linux (RHEL5)에서 테스트를 마쳤습니다. Windows에서 아직 테스트하지 않았습니다. –