문제

이진 파일에서 서명되지 않은 바이트를 읽고 싶습니다. 그래서 나는 다음 코드를 썼습니다.

#include <iostream>
#include <fstream>
#include <vector>
#include <istream>

std::string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;

std::basic_ifstream<unsigned char> inf(filename.c_str(), std::ios_base::in | std::ios_base::binary) ;
if (inF.good())
{
    std::vector<unsigned char> mDataBuffer;
    mDataBuffer.resize(bytesAvailable) ;
    inF.read(&mDataBuffer[0], toRead) ;
    size_t counted = inF.gcount() ;
}

이로 인해 변수 계수로 표시된대로 항상 0 바이트로 읽습니다.

웹 에서이 작업을 수행하기 위해 로케일을 설정해야한다고 말하는 것 같습니다. 이 작업을 수행하는 방법은 정확히 명확하지 않습니다.

동일한 코드는 '부호없는 char'대신 데이터 유형 'char'를 사용하여 작동합니다.

부호없는 Char를 사용하는 위의 코드는 Windows에서 작동하는 것으로 보이지만 Colinux Fedora 2.6.22.18에서 실행되지 않습니다.

Linux에서 작동하기 위해 무엇을해야합니까?

도움이 되었습니까?

해결책

C ++는 두 가지 버전의 문자 특성에 대한 명시 적 전문화를 제공하기 위해서만 구현이 필요합니다.

std::char_traits<char>
std::char_traits<wchar_t>

스트림과 문자열은 이러한 특성을 사용하여 EOF 값, 다양한 캐릭터 비교, 캐릭터를 INT로 확대하는 등 다양한 것들을 파악합니다.

스트림을 인스턴스화하는 경우

std::basic_ifstream<unsigned char>

스트림이 사용할 수있는 해당 캐릭터 특성 전문화 와이 전문화가 유용한 일을 수행하는지 확인해야합니다. 또한 스트림은 측면을 사용하여 실제 서식 및 숫자를 읽습니다. 마찬가지로 당신은 사람들의 전문 분야를 너무 수동으로 제공해야합니다. 표준은 기본 템플릿의 완전한 정의를 갖도록 구현을 요구하지 않습니다. 따라서 컴파일 오류를 얻을 수 있습니다.

오류 : Specialization std :: char_traits를 인스턴스화 할 수 없습니다.

나는 사용할 것이다 ifstream 대신 (a basic_ifstream<char>) 그리고 가서 가서 a로 읽으십시오 vector<char>. 벡터의 데이터를 해석 할 때는 여전히 데이터를 변환 할 수 있습니다. unsigned char 나중에.

다른 팁

특수화가 필요하므로 Basic_ifstream을 사용하지 마십시오.

정적 버퍼 사용 :

linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main( void )
{
        string filename("file");
        size_t bytesAvailable = 128;

        ifstream inf( filename.c_str() );
        if( inf )
        {
                unsigned char mDataBuffer[ bytesAvailable ];
                inf.read( (char*)( &mDataBuffer[0] ), bytesAvailable ) ;
                size_t counted = inf.gcount();
                cout << counted << endl;
        }

        return 0;
}
linux ~ $ g++ test_read.cpp
linux ~ $ echo "123456" > file
linux ~ $ ./a.out
7

벡터 사용 :

linux ~ $ cat test_read.cpp

#include <fstream>
#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main( void )
{
        string filename("file");
        size_t bytesAvailable = 128;
        size_t toRead = 128;

        ifstream inf( filename.c_str() );
        if( inf )
        {

                vector<unsigned char> mDataBuffer;
                mDataBuffer.resize( bytesAvailable ) ;

                inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
                size_t counted = inf.gcount();
                cout << counted << " size=" << mDataBuffer.size() << endl;
                mDataBuffer.resize( counted ) ;
                cout << counted << " size=" << mDataBuffer.size() << endl;

        }

        return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=128
7 size=7

첫 번째 통화에서 크기를 조정하는 대신 예비를 사용합니다.

linux ~ $ cat test_read.cpp

#include <fstream>
#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main( void )
{
        string filename("file");
        size_t bytesAvailable = 128;
        size_t toRead = 128;

        ifstream inf( filename.c_str() );
        if( inf )
        {

                vector<unsigned char> mDataBuffer;
                mDataBuffer.reserve( bytesAvailable ) ;

                inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
                size_t counted = inf.gcount();
                cout << counted << " size=" << mDataBuffer.size() << endl;
                mDataBuffer.resize( counted ) ;
                cout << counted << " size=" << mDataBuffer.size() << endl;

        }

        return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=0
7 size=7

보시다시피 .Resize (CARTED)를 호출하지 않고 벡터의 크기가 잘못됩니다. 그것을 명심하십시오. 캐스팅 참조를 사용하는 것이 일반적입니다 cppreference

훨씬 쉬운 방법 :

#include <fstream>
#include <vector>

using namespace std;


int main()
{
    vector<unsigned char> bytes;
    ifstream file1("main1.cpp", ios_base::in | ios_base::binary);
    unsigned char ch = file1.get();
    while (file1.good())
    {
        bytes.push_back(ch);
        ch = file1.get();
    }
    size_t size = bytes.size();
    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top