繁体   English   中英

为什么 std::istream::ignore 丢弃字符?

[英]Why does std::istream::ignore discard characters?

std::istream::ignoreCPlusPlus 网站上,它说

istream& ignore (streamsize n = 1, int delim = EOF);

提取和丢弃字符

从输入序列中提取字符并丢弃它们,直到提取了 n 个字符,或者一个比较等于 delim。

为什么它说它丢弃它们而不是返回它们

编辑

根据要求,这是有问题的特定代码。 它是一个回调函数,服务器端,处理发送的客户端文件( _data

static void loadFile (const std::string &_fileName, std::vector<char> &_data)                                                                                            
{
    std::ifstream ifs;
    ifs.exceptions(std::ifstream::failbit);
    ifs.open(_fileName, std::ifstream::in | std::ifstream::binary);
    auto startPos = ifs.tellg();
    ifs.ignore(std::numeric_limits<std::streamsize>::max());
    auto size = static_cast<std::size_t>(ifs.gcount());
    ifs.seekg(startPos);
    _data.resize(size);
    ifs.read(_data.data(), size);
    std::cout << "loaded " << size << " bytes" << std::endl;
}   

为什么它说它丢弃它们而不是返回它们?

因为还有其他函数可以返回它们。 std::istream::getlinestd::getline


更新

更新后的帖子中以下几行的全部目的是获取文件的大小。

auto startPos = ifs.tellg();
ifs.ignore(std::numeric_limits<std::streamsize>::max());
auto size = static_cast<std::size_t>(ifs.gcount());

这是我第一次看到使用istream::ignore()来做到这一点。 您还可以使用以下内容来获取文件的大小。

// Find the end of the file
ifs.seekg(0, std::ios::end);

// Get its position. The returned value is the size of the file.
auto size = ifs.tellg();
auto startPos = ifs.tellg();

这将存储(刚刚打开的)文件开头的位置。

ifs.ignore(std::numeric_limits<std::streamsize>::max());

这会读取整个文件(直到 EOF)并丢弃读取的内容。

auto size = static_cast<std::size_t>(ifs.gcount());

gcount返回上次未格式化输入操作读取的字符数,在本例中为ignore 由于ignore读取文件中的每个字符,这是文件中的字符数。

ifs.seekg(startPos);

这会将流重新定位回文件的开头,

_data.resize(size);

...分配足够的空间来存储整个文件的内容,

ifs.read(_data.data(), size);

最后再次将其读入_data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM