简短回答
只需包括
#include <boost/iostreams/seek.hpp>
并使用seek http://www.boost.org/doc/libs/1_42_0/libs/iostreams/doc/functions/seek.html功能如
boost::iostreams::seek(device, offset, whence);
where
-
device
是文件、流、streambuf 或任何可转换为的对象seekable
;
-
offset
是类型的 64 位偏移量stream_offset http://www.boost.org/doc/libs/1_42_0/libs/iostreams/doc/functions/positioning.html#synopsis;
-
whence
is BOOST_IOS::beg
, BOOST_IOS::cur
or BOOST_IOS::end
.
返回值seek
属于类型std::streampos
,并且它可以转换为stream_offset
使用position_to_offset http://www.boost.org/doc/libs/1_42_0/libs/iostreams/doc/functions/positioning.html#position_to_offset功能。
Example
这是一个冗长、乏味且重复的示例,它展示了如何打开两个文件、寻找 >4GB 的偏移量以及在它们之间复制数据。
警告:此代码将创建非常大的文件(几个 GB)。在支持稀疏文件的操作系统/文件系统上尝试此示例。 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();
}