【问题标题】:Questions about unsigned char, char, BYTE, and file writing关于unsigned char、char、BYTE和文件写入的问题
【发布时间】: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 *。所以问题如下:

  1. 我是否正确写入文件?如果不是,正确的方法是什么。
  2. 如何将 char 向量转换为 unsigned char 向量?

谢谢。

【问题讨论】:

    标签: c++ string file vector


    【解决方案1】:

    您在这里遇到了范围问题。在你说BYTE *rgbPlaintext = (BYTE*)&amp;contents[0] ; 的地方,你在if 语句后面的花括号内声明了一个名为rgbPlaintext 的变量。从编译器的角度来看,这与您在程序开头声明的 rgbPlaintext 不同。一旦你为第二个rgbPlaintext 赋值,你就会遇到右花括号,这只会导致该值被丢弃。

    顶部的语句应该是

    BYTE *rgbPlaintext;
    

    结束大括号之前的最后一条语句应该是

    rgbPlaintext =  (BYTE*)&contents[0] ;
    

    没有 BYTE * 部分。

    这样,您仍然可以在if 语句后面的代码中访问rgbPlaintext

    【讨论】:

    • 我删除了 BYTE 部分,现在它给出了一个错误:表达式必须是可修改的值
    • 注意星号的位置很重要。你的第一个声明应该是BYTE* rgbPlaintext; 而不是BYTE rgbPlaintext[] = {0x00};。那么if 语句底部的引用应该只是一个引用,而不是定义,例如,rgbPlaintext = (BYTE*)&amp;contents[0] ; 而不是BYTE *rgbPlaintext = (BYTE*)&amp;contents[0] ;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多