7

ブースト iostreams は、セミポータブルな方法で大きなファイルへの 64 ビット アクセスをサポートしていると思われることを読みました。彼らの FAQ には64 ビット オフセット関数が記載されていますが、それらの使用方法の例はありません。大きなファイルを処理するためにこのライブラリを使用した人はいますか? 2 つのファイルを開き、中間をシークし、一方を他方にコピーする簡単な例は非常に役に立ちます。

ありがとう。

4

1 に答える 1

7

簡潔な答え

含めるだけ

#include <boost/iostreams/seek.hpp>

seek次のように関数を使用します

boost::iostreams::seek(device, offset, whence);

どこ

  • deviceファイル、ストリーム、streambuf、または に変換可能な任意のオブジェクトseekableです。
  • offset型の 64 ビット オフセットですstream_offset
  • whenceBOOST_IOS::begBOOST_IOS::curまたはBOOST_IOS::end。_

の戻り値seekは 型で、関数を使用してstd::streamposに変換できます。stream_offsetposition_to_offset

以下は、2 つのファイルを開き、4 GB を超えるオフセットを探し、それらの間でデータをコピーする方法を示す、長くて退屈で繰り返しの多い例です。

警告: このコードは非常に大きなファイル (数 GB) を作成します。スパース ファイルをサポートする OS/ファイル システムでこの例を試してください。Linux は問題ありません。Windows などの他のシステムではテストしていません。

/*
 * WARNING: This creates very large files (several GB)
 * unless your OS/file system supports sparse files.
 */
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/positioning.hpp>
#include <cstring>
#include <iostream>

using boost::iostreams::file_sink;
using boost::iostreams::file_source;
using boost::iostreams::position_to_offset;
using boost::iostreams::seek;
using boost::iostreams::stream_offset;

static const stream_offset GB = 1000*1000*1000;

void setup()
{
    file_sink out("file1", BOOST_IOS::binary);
    const char *greetings[] = {"Hello", "Boost", "World"};
    for (int i = 0; i < 3; i++) {
        out.write(greetings[i], 5);
        seek(out, 7*GB, BOOST_IOS::cur);
    }
}

void copy_file1_to_file2()
{
    file_source in("file1", BOOST_IOS::binary);
    file_sink out("file2", BOOST_IOS::binary);
    stream_offset off;

    off = position_to_offset(seek(in, -5, BOOST_IOS::end));
    std::cout << "in: seek " << off << std::endl;

    for (int i = 0; i < 3; i++) {
        char buf[6];
        std::memset(buf, '\0', sizeof buf);

        std::streamsize nr = in.read(buf, 5);
        std::streamsize nw = out.write(buf, 5);
        std::cout << "read: \"" << buf << "\"(" << nr << "), "
                  << "written: (" << nw << ")" << std::endl;

        off = position_to_offset(seek(in, -(7*GB + 10), BOOST_IOS::cur));
        std::cout << "in: seek " << off << std::endl;
        off = position_to_offset(seek(out, 7*GB, BOOST_IOS::cur));
        std::cout << "out: seek " << off << std::endl;
    }
}

int main()
{
    setup();
    copy_file1_to_file2();
}
于 2010-02-26T15:30:37.633 に答える