2012-01-10 4 views
0

이진 입/출력을 테스트하는 비교적 간단한 프로그램을 테스트 중입니다. 기본적으로 헤더 (문자열)와 일부 데이터 (두 배)가있는 파일을 작성하고 있습니다. 코드는 다음과 같다 :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의 사용법을 어딘가에서 놓치고있을 것입니다.

+0

작품을 작동합니다. "Read header : Header \ n Read data size : 100 \ n"then 100 테스트 입출력 ... – Naddiseo

+0

Visual Studio 2010을 사용하여 나를 위해 일합니다. – shengy

+0

그건 이상합니다. 그것은 나를 위해 작동하지 않습니다. 코드는 그대로, 크기 0의 데이터를 읽는 인쇄물이므로 그 다음에 나오는 인쇄 섹션에서 구분됩니다. Cygwin 및 Linux (RHEL5)에서 테스트를 마쳤습니다. Windows에서 아직 테스트하지 않았습니다. –

답변

1

코드가 제대로 실행됩니다. 그러나 파일이 쓰기 위해 성공적으로 열렸는지 결코 확인하지 않으므로 시스템에서 자동으로 실패 할 수 있습니다. 당신이 ofs 열 후에는

if (!ofs) { 
    std::cout << "Could not open file for writing" << std::endl; 
    return 1; 
} 

을 추가해야합니다 그리고 같은 것은 당신이 ifs

if (!ifs) { 
    std::cout << "Could not open file for reading" << std::endl; 
    return 1; 
} 

또는 그 라인을 따라 뭔가를 연 후. 또한 내가 존재하는지 아닌지를 동일하게하기 때문에 파일이 먼저 존재하는지 확인하는 이유를 이해할 수 없습니다.

+0

댓글을 주셔서 감사합니다. 그러나 이것은 데이터를 전체적으로 읽는 실제 문제, 즉 헤더와 복식을 해결하지 않는 비교적 사소한 문제입니다 (제 생각 엔). –

+0

그래도 사용해 보셨습니까? 당신이 게시 한 코드는 나를 위해 잘 작동합니다 _unless_ 나는'data.bin' 파일을 열 수 없습니다. 어떤 경우에는 충돌합니다. –

+0

감사. 당신 말이 맞아요. if (ofs)가 실패했을 때 열리고 충돌 할 때 작동합니다 (실패 비트). 나는 이것을 고쳤다. 그것은 나에게 약간의 아이디어를 준다. –

0

이 나를 위해

#include <iostream> 
using std::cout; 
using std::cerr; 
using std::cin; 
using std::endl; 
#include <fstream> 
using std::ifstream; 
#include <cstdint> 

int main() { 

    ifstream fin; 
    fin.open("input.dat", std::ios::binary | std::ios::in); 
    if (!fin) { 
     cerr << "Cannot open file " << "input.dat" << endl; 
     exit(1); 
    } 

    uint8_t input_byte; 
    while (fin >> input_byte) { 
     cout << "got byte " << input_byte << endl; 
    } 

    return 0; 
}