[英]Why does std::istream::ignore discard characters?
On the CPlusPlus website for std::istream::ignore
, it says在
std::istream::ignore
的CPlusPlus 网站上,它说
istream& ignore (streamsize n = 1, int delim = EOF);
Extract and discard characters
提取和丢弃字符
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
从输入序列中提取字符并丢弃它们,直到提取了 n 个字符,或者一个比较等于 delim。
Why does it say it discards them rather than returns them ?为什么它说它丢弃它们而不是返回它们?
EDIT编辑
As requested, here is the particular code in question.根据要求,这是有问题的特定代码。 It is a callback function, server-side, processing the client file that was sent (
_data
)它是一个回调函数,服务器端,处理发送的客户端文件(
_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;
}
Why does it say it discards them rather than returns them?
为什么它说它丢弃它们而不是返回它们?
Because there are other functions to return them.因为还有其他函数可以返回它们。 See
std::istream::getline
and std::getline
见
std::istream::getline
和std::getline
Update更新
The whole purpose of the following lines in your updated post is to obtain the size of the file.更新后的帖子中以下几行的全部目的是获取文件的大小。
auto startPos = ifs.tellg();
ifs.ignore(std::numeric_limits<std::streamsize>::max());
auto size = static_cast<std::size_t>(ifs.gcount());
This is the first time I have seen use of istream::ignore()
to do that.这是我第一次看到使用
istream::ignore()
来做到这一点。 You could also use the following to get the size of the file.您还可以使用以下内容来获取文件的大小。
// 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();
This stores the position at the beginning of the (just-opened) file.这将存储(刚刚打开的)文件开头的位置。
ifs.ignore(std::numeric_limits<std::streamsize>::max());
This reads through the entire file (until EOF) and discards the content read.这会读取整个文件(直到 EOF)并丢弃读取的内容。
auto size = static_cast<std::size_t>(ifs.gcount());
gcount
returns the number of characters read by the last unformatted input operation, in this case, the ignore
. gcount
返回上次未格式化输入操作读取的字符数,在本例中为ignore
。 Since the ignore
read every character in the file, this is the number of characters in the file.由于
ignore
读取文件中的每个字符,这是文件中的字符数。
ifs.seekg(startPos);
This repositions the stream back to the beginning of the file,这会将流重新定位回文件的开头,
_data.resize(size);
...allocates enough space to store the entire file's content, ...分配足够的空间来存储整个文件的内容,
ifs.read(_data.data(), size);
and finally reads it again into _data
.最后再次将其读入
_data
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.