1

バイナリテキストを読み込む必要のあるプログラムがあります。リダイレクトを介してバイナリテキストを読みました:

readDataは、Makefileによって作成された実行可能ファイルになります。

例:readData <binaryText.txt

私がやりたいのは、バイナリテキストを読み取り、各文字を文字配列内の文字としてバイナリテキストファイルに格納することです。バイナリテキストは32で構成されていますこれは私の試みです...

unsigned char * buffer;
char d;
cin.seekg(0, ios::end);
int length = cin.tellg();
cin.seekg(0, ios::beg);
buffer = new unsigned char [length];
while(cin.get(d))
{
  cin.read((char*)&buffer, length);
  cout << buffer[(int)d] << endl;
}

ただし、これでセグメンテーション違反が発生し続けます。バイナリテキストをchar配列に読み込む方法について誰かが何かアイデアを持っているでしょうか?ありがとう!

4

4 に答える 4

0

私は C++ というより C プログラマーですが、while ループを開始するべきだったと思います。

while(cin.get(&d)){
于 2012-12-03T00:58:11.490 に答える
0

最も簡単なのは次のようになります。

std::istringstream iss;
iss << std::cin.rdbuf();

// now use iss.str()

または、すべて 1 行で:

std::string data(static_cast<std::istringstream&>(std::istringstream() << std::cin.rdbuf()).str());
于 2012-12-03T01:07:10.300 に答える
0

このようなものがうまくいくはずです。引数からファイル名を取得し、ファイル全体を一度に読み取ります。

const char *filename = argv[0];
vector<char> buffer;

// open the stream
std::ifstream is(filename);

// determine the file length
is.seekg(0, ios_base::end);
std::size_t size = is.tellg();
is.seekg(0, std::ios_base::beg);

// make sure we have enough memory space
buffer.reserve(size);
buffer.resize(size, 0);

// load the data
is.read((char *) &buffer[0], size);

// close the file
is.close();

vector次に、文字を読み取るために を反復処理するだけです。

于 2012-12-03T01:10:14.450 に答える