文件流寻求正确的位置,而 fstream 不会

Filestream seeks correct position whereas fstream doesn't

本文关键字:位置 fstream 不会 文件      更新时间:2023-10-16

在C#

FileStream fs("file.bin",/*Open in binary, read only mode*/);
var bytes = new byte[100];
fs.Seek(20000000, SeekOrigin.Begin); //*20000000*
fs.Read(bytes, 0, 100);

在C 中,istream总是变为null

typedef std::shared_ptr<boost::iostreams::mapped_file_source> FileStream;
FileStream fs = FileStream(new boost::iostreams::mapped_file_source("file.bin", 100, 0));
if (fs->is_open())
{
    boost::iostreams::stream<boost::iostreams::mapped_file_source> is(*fs.get());
    if (is.seekg(20000000, is.beg))
        //read 100 characters from 20000000th position
    fs->close();
}

如果我更改 boost::iostreams::stream<boost::iostreams::mapped_file_source> is(*fs.get());

进入 boost::iostreams::stream<boost::iostreams::mapped_file_source> is("file.bin");

is是初始化的,但读取到20000000th字节仍然是不可能的。错误发生与未找到文件时完全相同。

您被淘汰告诉mapped_file_source,要映射的最大文件大小为100字节。那么,为什么您认为您可以进入20000000的位置并阅读任何内容?

请参阅mapped_file_source上的参考

概述:默认情况下,打开之前必须存在文件,并且不被截断;试图通过文件的末尾写入错误会导致错误。

构造函数文档:长度 - 要映射的字节数。如果未指定此参数,则将映射整个文件。