代码之家  ›  专栏  ›  技术社区  ›  Queueless

有人能提供一个使用boost-iostreams查找、读取和写入大于4GB文件的示例吗

  •  7
  • Queueless  · 技术社区  · 16 年前

    64 bit offset functions ,但没有关于如何使用它们的例子。有人用这个库来处理大文件吗?打开两个文件,找到它们的中间位置,然后将一个文件复制到另一个文件的简单示例将非常有用。

    谢谢。

    1 回复  |  直到 16 年前
        1
  •  7
  •   Danilo Piazzalunga    16 年前

    简答

    只需包括

    #include <boost/iostreams/seek.hpp>
    

    seek 功能如

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

    哪里

    • device 是一个文件、流、streambuf或任何可转换为 seekable ;
    • offset 是类型为64位的偏移量 stream_offset ;
    • whence BOOST_IOS::beg , BOOST_IOS::cur BOOST_IOS::end .

    返回值为 寻求 std::streampos ,它可以转换为 stream_offset 使用 position_to_offset 功能。

    /*
     * 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();
    }