2011-06-13 16 views
7

私はバイナリデータをC++で読み書きする必要があります。私はofstreamifstreamクラスから使用しますが、9,13,32のような文字を読み取ることはできません。テーマを読み書きする別の方法があるかどうか。C++でバイナリデータを読むにはどうしたらいいですか?

+2

あなたのコードを表示してください。オープンモードのフィールドに 'std :: ifstream :: binary'を設定しましたか? –

+0

コードのスニペット、期待する出力、得られた出力を表示してください。 –

+0

を参照してくださいhttp://stackoverflow.com/questions/5355163/writing-binary-data-stdstring-to-an-stdofstream – davka

答えて

2

はこれを行いプログラムである:ここでは

#include <iostream> 
#include <fstream> 

int main(int argc, const char *argv[]) 
{ 
    if (argc < 2) { 
     ::std::cerr << "Usage: " << argv[0] << "<filename>\n"; 
     return 1; 
    } 
    ::std::ifstream in(argv[1], ::std::ios::binary); 
    while (in) { 
     char c; 
     in.get(c); 
     if (in) { 
     ::std::cout << "Read a " << int(c) << "\n"; 
     } 
    } 
    return 0; 
} 

は、それがLinux上で実行されているの例です。

$ echo -ne '\x9\xd\x20\x9\xd\x20\n' >binfile 
$ ./readbin binfile 
Read a 9 
Read a 13 
Read a 32 
Read a 9 
Read a 13 
Read a 32 
Read a 10 
+8

パラノイド名前空間の解決! :-) –

+0

@Kerrek SB:なぜ、はい、http://stackoverflow.com/questions/1661912/why-does-everybody-use-unanchored-namespace-declarations-ie-std-not-std *大きな笑顔を見てください* – Omnifarious

+0

これは機能しますが、ファイルが大きい場合は非常に非効率です。パフォーマンスを向上させるには、Stuard Golodetzメソッドを使用します。パフォーマンスをさらに向上させるには、std :: streambufを使用します。 – user763305

6

std::ios::binaryフラグを使用してファイルを開き、ストリーミング演算子ではなくreadwriteを使用します。

そこにはいくつかの例はここにある:ここでは

http://www.cplusplus.com/reference/iostream/istream/read/

http://www.cplusplus.com/reference/iostream/ostream/write/

+1

もっと説明してください。 –

+2

@mehdi、彼はあなたにドキュメンテーションとサンプルをくれました。何をもっとしたいですか? – Beta

+0

最初のリンクの例を見てください。ファイルを開き、内容を読み込んで内容をcharバッファに入れます。バッファは基本的にバイトの配列として扱われます。まさにあなたは何の説明が必要なのでしょうか?どのようにバッファを処理し、そこから値を取るか? – rzetterberg

1

これは基本的な例である(いずれかのエラーチェックなし!):

// Required STL 
#include <fstream> 
using namespace std; 

// Just a class example 
class Data 
{ 
    int a; 
    double b; 
}; 

// Create some variables as examples 
Data x; 
Data *y = new Data[10]; 

// Open the file in input/output 
fstream myFile("data.bin", ios::in | ios::out | ios::binary); 

// Write at the beginning of the binary file 
myFile.seekp(0); 
myFile.write((char*)&x, sizeof (Data)); 

... 

// Assume that we want read 10 Data since the beginning 
// of the binary file: 
myFile.seekg(0); 
myFile.read((char*)y, sizeof (Data) * 10); 

// Remember to close the file 
myFile.close(); 
+0

標準準拠のコンパイラはこのファイルをビルドしません。 ** 'std ::' ** 'fstream'は' '(' .h'はありません)です。 – Johnsyweb

+0

適用された提案..遅れて申し訳ありません!なぜ@ johnsywebが自分のコードを編集しなかったのですか? – gmas80

関連する問題