C++バイナリファイル読み書き

6702 ワード


 
 
バイナリファイルの読み書き
  ①put()
put()関数はストリームに1つの文字を書き込み、その原型はofstream&put(char ch)であり、file 1のような使用も比較的簡単である.put('c');ストリームに「c」という文字を書きます.
  ②get()
get()関数は比較的柔軟で、3つの一般的なリロード形式があります.
1つはput()に対応する形式:ifstream&get(char&ch);機能は、ストリームから文字を読み出し、結果を参照chに保存し、ファイルの最後に空の文字を返すことです.例えばfile 2.get(x);ファイルから1文字を読み出し、読み出した文字をxに保存することを示す.
もう1つのリロード形式のプロトタイプはint get();この形式は、ストリームから1文字を返し、ファイルの最後に達するとx=file 2のようなEOFを返す.get();前例の機能と同じです.
もう一つの形式の原型はifstream&get(char*buf,int num,char delim=');この形式では、num文字が読み込まれたりdelimで指定された文字に遭遇したりするまでbufが指す配列に文字を読み込み、delimというパラメータを使用しない場合はデフォルト値の改行文字を使用します'.例:
  file2.get(str1,127,'A');//ファイルから文字列str 1に文字を読み出し、文字'A'に遭遇したり127文字を読み出したりした場合に終了する.
③読み書きデータブロック
バイナリ・データ・ブロックを読み書きするには、メンバー関数read()とwrite()のメンバー関数を使用します.これらのモデルは次のとおりです.
  read(unsigned char *buf,int num);
  write(const unsigned char *buf,int num);
read()ファイルからnum文字をbuf指向キャッシュに読み出し、num文字が読み込まれていないときにファイルの最後になった場合は、メンバー関数int gcount()を使用します.実際に読み取った文字数を取得します.一方、write()はbufが指すキャッシュからnum文字をファイルに書き込む場合、キャッシュのタイプがunsigned char*であり、タイプ変換が必要な場合があることに注意してください.
原文は【ビットネット】から出て、転載は原文のリンクを保留してください:http://soft.chinabyte.com/database/460/11433960.shtml
 
http://www.cplusplus.com/doc/tutorial/files/
 
//reading a complete binary file
 
In binary files, to input and output data with the extraction and insertion operators (<< and>>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...). File streams include two member functions specifically designed to input and output binary data sequentially:write and read. The first one (write) is a member function ofostream inherited by ofstream. And read is a member function ofistream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are: write ( memory_block, size ); read ( memory_block, size ); Where memory_block is of type "pointer to char"(char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. Thesize parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.
アイデアはifstream::pos_type size;
 
// reading a complete binary file
#include <iostream>
#include <fstream>
using namespace std;

ifstream::pos_type size; char * memblock;

int main () {
  ifstream file ("example.bin", ios::in|ios::binary|ios::ate);
  if (file.is_open())
  {
    size = file.tellg();     memblock = new char [size];     file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();

    cout << "the complete file content is in memory";

    delete[] memblock;
  }
  else cout << "Unable to open file";
  return 0;
}

 
 
In this example the entire file is read and stored in a memory block. Let's examine how this is done: First, the file is open with the ios::ate flag, which means that the get pointer will be positioned at the end of the file. This way, when we call to membertellg(), we will directly obtain the size of the file. Notice the type we have used to declare variablesize:
 
ifstream::pos_type size;

ifstream::pos_type is a specific type used for buffer and file positioning and is the type returned byfile.tellg(). This type is defined as an integer type, therefore we can conduct on it the same operations we conduct on any other integer value, and can safely be converted to another integer type large enough to contain the size of the file. For a file with a size under 2GB we could use int:
1
2
int size;
size = (int) file.tellg();

Once we have obtained the size of the file, we request the allocation of a memory block large enough to hold the entire file:
 
memblock = new char[size];

Right after that, we proceed to set the get pointer at the beginning of the file (remember that we opened the file with this pointer at the end), then read the entire file, and finally close it:
1
2
3
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();

At this point we could operate with the data obtained from the file. Our program simply announces that the content of the file is in memory and then terminates.
Buffers and Synchronization
When we operate with file streams, these are associated to an internal buffer of typestreambuf. This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with anofstream, each time the member function put (which writes a single character) is called, the character is not written directly to the physical file with which the stream is associated. Instead of that, the character is inserted in that stream's intermediate buffer. When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream) or simply freed (if it is an input stream). This process is calledsynchronization and takes place under any of the following circumstances:
  • When the file is closed: before closing a file all buffers that have not yet been flushed are synchronized and all pending data is written or read to the physical medium.
  • When the buffer is full: Buffers have a certain size. When the buffer is full it is automatically synchronized.
  • Explicitly, with manipulators: When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are:flush and endl.
  • Explicitly, with member function sync(): Calling stream's member functionsync(), which takes no parameters, causes an immediate synchronization. This function returns anint value equal to -1 if the stream has no associated buffer or in case of failure. Otherwise (if the stream buffer was successfully synchronized) it returns0.