【发布时间】:2016-08-02 04:06:34
【问题描述】:
我有一个向量定义如下:
std::vector<char> contents;
我的目标是将文件读入 BYTE 数组,这是 unsigned char 的 typedef。我的尝试如下:
BYTE rgbPlaintext[] = {0x00};
std::ifstream in;
std::vector<char> contents;
in.open("test.dat", std::ios::in | std::ios::binary);
if (in.is_open())
{
// get the starting position
std::streampos start = in.tellg();
// go to the end
in.seekg(0, std::ios::end);
// get the ending position
std::streampos end = in.tellg();
// go back to the start
in.seekg(0, std::ios::beg);
// create a vector to hold the data that
// is resized to the total size of the file
contents.resize(static_cast<size_t>(end - start));
// read it in
in.read(&contents[0], contents.size());
BYTE *rgbPlaintext = (BYTE*)&contents[0] ;
}
但是当我将 rgbPlainText 写入文件时,使用以下内容:
std::ofstream f("testOut.dat",std::ios::out | std::ios::binary);
for(std::vector<char>::const_iterator i = contents.begin(); i != contents.end(); ++i)
{
f << *rgbPlaintext;
}
这只是一行空值。 test.dat 文件包含清晰的文本。我怎样才能让它正常工作?当我将向量更改为 unsigned char 而不是现在定义的 char 时,在“读入”步骤中出现错误,说预期的参数类型是 char * 而输入的参数是 unsigned char *。所以问题如下:
- 我是否正确写入文件?如果不是,正确的方法是什么。
- 如何将 char 向量转换为 unsigned char 向量?
谢谢。
【问题讨论】: