2017-04-22 1 views
0

나는 상황을 어떻게 처리해야 하는지를 정말로 이해할 수 없기 때문에 문제가있다. char *를 basic_streambuf에 쓰고 ifstream에 할당하기

나는 X 크기의 char* 버퍼, 그것을 해독있어 다음 내가을 편집 할 수 ifstream 핸들러 클래스 에 의해 구문 분석됩니다 암호화 된 파일의 내용입니다 있습니다.

그래서 내 생각은 으로 sputn으로 버퍼를 할당하는 fstream 개체를 만드는 것이 었습니다.

fstream _handle2; _handle2.rdbuf()->sputn(_buffer, _size); _handle2.flush();

그러나 물론

, 그것은 작동하지 않는 버퍼가 당신이 그것을 그렇게 만드는 방법의 아이디어를 가지고 마십시오 fstream 객체에 기록되지 않습니다?

다른 방법을 시도했지만 분명히 무엇을 해야할지 알 수 없습니다.

+1

왜 쓰기를 사용하지 않는? 'handle2.write (buffer, size);' – Aconcagua

+0

시도했지만, 작동하지 않았습니다 ... 버퍼를 읽으려고 시도합니다. – d3vil401

+0

fstream을 어떻게 열었습니까? fstream은 파일에 데이터를 쓰거나 읽을 수 있도록 설계되었습니다. 파일에 연결되어 있지 않으면 출력되지 않습니다. 그러나 실제로 실현하고자하는 것은 무엇입니까? 전체 파일 내용을 일종의 데이터 버퍼로 읽어들입니까? ifstream이 파일 내용을 읽으면 e를 읽을 수 있습니다. 지. char c를 통해 바이트 단위로; 스트림 >> c;'. – Aconcagua

답변

0

ifstream과 유사하게 구문 분석 할 수있는 버퍼 유형을 만들려고합니다.

당신은 (이미 댓글에서 제공하는 link에서 채택)이 같은 시도 할 수 있습니다 :에 텍스트를 변환하는 데 사용됩니다

std::istringstream : 귀하의 코멘트에 응답

std::ifstream ifs("test.txt", std::ifstream::binary); 
if (ifs) 
{ 
    ifs.seekg (0, ifs.end); 
    int length = ifs.tellg(); 
    ifs.seekg (0, ifs.beg); 

    std::string buffer; 
    buffer.resize(length); 
    ifs.read(const_cast<char*>(buffer.data()), length); 
    if (ifs) 
    { 
     // de-crypt the buffer here! 
     // something like: 
     // buffer[i] = decryptChar(buffer[i]); 

     std::istringstream iss(buffer); 

     // now you can use iss just the same way as ifs, 
     // if the file was not encrypted... 

    } 
    else 
    { 
     std::cout << "error: only " << ifs.gcount() << " bytes could be read"; 
    } 
    ifs.close(); 
} 

편집 2 진 데이터, 지. int n; iss >> n;은 아스키 시퀀스 0x32, 0x30, 0x31, 0x30, 0x32, 0x30, 0x31, 0x32로 표현되는 문자열 "20102012"를 0x0132bb7c의 해당 4 바이트 정수 값으로 변환합니다. 그러나 데이터 이 이미 인 경우 std::istringstream은 적합하지 않습니다. 그렇지 않으면, 당신이 적절하게 이들의 바이트 정렬을 제어하는 ​​다음,하지만, 확인 - 당신은 복잡한 데이터 형식이 클래스를 사용할 수

class DecryptionStream 
{ 
    std::unique_ptr<char> mBuffer; 
    char* mEnd; 
    char* mPos; 
    unsigned int flags; 

    unsigned int const eofbit = 1 << 0; 
    unsigned int const failbit = 1 << 1; 
    // other flag bits as needed 

public: 
    // fail/eof bits as needed 
    DecryptionStream(char const* fileName) : mPos(nullptr) 
    { 
     std::ifstream ifs(fileName, std::ifstream::binary); 
     if (ifs) 
     { 
      ifs.seekg (0, ifs.end); 
      int length = ifs.tellg(); 
      ifs.seekg (0, ifs.beg); 

      mBuffer.reset(new char[length]); 
      ifs.read(mBuffer.get(), length); 
      if (ifs) 
      { 
       // de-crypt the buffer here! 
       // something like: 
       // buffer[i] = decryptChar(buffer[i]); 
       mPos = mBuffer.get(); 
       mEnd = mBuffer.get() + length; 
      } 
      else 
      { 
       flags |= failbit; 
      } 
      ifs.close(); 
     } 
    } 

    template<typename T> 
    DecryptionStream& operator >>(T& t) 
    { 
     // fail, if any fail bit set already 
     size_t avail = mPos - mEnd; 
     if (avail < sizeof(t)) 
     { 
      flags |= eofbit | failbit; 
     } 
     else 
     { 
      if(avail == sizeof(t)) 
      { 
       flags |= eofbit; 
      } 
      memcpy(&t, mPos, sizeof(t)); 
      mPos += sizeof(t); 
     } 
     return *this; 
    } 

    operator bool() 
    { 
     return flags == 0; 
    } 
}; 

: 그럼 당신은 오히려이 예와 유사하게 자신의 스트림 클래스를 작성하려고 할 수도 있습니다 너는 틀리게 실패 할지도 모른다!

+0

정확히 내가 요구했던 것이 아니었지만,이 코드의 일부로 나는 내가했던 것을 조금 할 수 있었다. 감사. – d3vil401

+0

이제는 핸들링 문자열이 아닌 원시 바이너리 버퍼입니다. ios :: binary 플래그를 추가했지만 버퍼의 일부를 올바르게 읽지 못하는 것 같습니다. – d3vil401

+0

이진 컨텐츠? 'std :: istringstream'은 적합하지 않습니다. 내 anser를 적절하게 확장했습니다. – Aconcagua

0

boost::iostreams::array_source을 살펴보십시오.

배열을 std::istream으로 처리 할 수 ​​있습니다. std::istringstream 이상의 장점은 배열을 스트림으로 복사하지 않아 메모리 사용량을 줄이고 성능을 향상시키는 것입니다. array_source은 기존 버퍼에 대한 포인터를 저장합니다.

#include <iostream> 
#include <string> 
#include <boost/iostreams/device/array.hpp> 
#include <boost/iostreams/stream.hpp> 
namespace io = boost::iostreams; 

int main() 
{ 
    // Create an array and wrap a stream interface around it. 
    const char buffer[] = "hello stackoverflow"; 
    io::stream<io::array_source> strm(buffer, sizeof(buffer) - 1); //-1 to strip '\0' 

    // Use the stream like a standard istream. 
    std::string s; 
    while(strm >> s) 
     std::cout << s << "\n"; 
} 

Live Demo on Coliru.