如何阅读文件到从性病:: ifstream的无符号的字符数组? [英] How to read a file into unsigned char array from std::ifstream?
问题描述
所以我normaly做的东西,如:
So normaly I do stuff like:
std::ifstream stream;
int buff_length = 8192;
boost::shared_array<char> buffer( new char[buff_length]);
stream.open( path.string().c_str(), std::ios_base::binary);
while (stream)
{
stream.read(buffer.get(), buff_length);
//boost::asio::write(*socket, boost::asio::buffer(buffer.get(), stream.gcount()));
}
stream.close();
我不知道如何读入 unsigned char型
缓冲(的boost :: shared_array&LT; unsigned char型&GT;缓冲区(新的无符号的char [buff_length]);
)
推荐答案
在一个最简单的形式:
std::vector<unsigned char> vec(
std::istreambuf_iterator<char>(std::cin)
, std::istreambuf_iterator<char>()
);
替换的std :: CIN
与您的实际数据流。
以上是有可能做一个以上的内存分配(除极少数字节的文件),因为的std :: istreambuf_iterator&LT;&GT;
是一个输入迭代器,而不是一个随机存取或前向迭代器,因此该文件的长度不能减去迭代器来衡量,比如结束 - 开始
或致电性病::距离(开始,结束)
。可如果创建矢量被减少到一个内存分配第一个空,那么的std ::矢量&lt;&GT; ::储备()
被称为为文件分配内存,长度和最后插入范围被称为 vec.insert(vec.end(),乞讨,结束)
与求
和结束
是的std :: istreambuf_iterator&LT;方式&gt;
如上读取整个文件
The above is likely to do more than one memory allocation (for files larger than a very few bytes) because std::istreambuf_iterator<>
is an input-iterator, not a random-access or a forward iterator, so the length of the file can't be measured by subtracting iterators like end - begin
or calling std::distance(begin, end)
. It can be reduced to one memory allocation if the vector is created first empty, then std::vector<>::reserve()
is called to allocate memory for the file length and finally range insert is called vec.insert(vec.end(), beg, end)
with beg
and end
being std::istreambuf_iterator<>
as above to read the entire file.
如果文件大小更然后几个千字节它可能是最有效的把它映射到进程内存,避免从内核到用户空间复制内存。
If the file size is more then a few kilo-bytes it may be most efficient to map it into the process memory to avoid copying memory from the kernel to user-space.
究其原因的std :: istreambuf_iterator&LT;焦炭&GT;
则采用的是因为实现使用的std :: char_traits&LT;&GT;
通常只具有字符
和 wchar_t的
专业。无论如何,C和C ++标准要求所有的字符
类型有没有填充位相同的二进制布局,所以字符$ C $之间的转换C>,
unsigned char型
和符号字符
(这是完全不同的类型,不像符号int
和 INT
是同一类型)preserve位模式,因此是安全的。
The reason std::istreambuf_iterator<char>
is used is because the implementation uses std::char_traits<>
which normally has specializations only for char
and wchar_t
. Regardless, the C and C++ standards require all char
types to have the same binary layout with no padding bits, so conversions between char
, unsigned char
and signed char
(which are all distinct types, unlike signed int
and int
being the same type) preserve bit patterns and thus are safe.
这篇关于如何阅读文件到从性病:: ifstream的无符号的字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!