【问题标题】:Read/write to file, bytes go missing, might be char overflow读/写文件,字节丢失,可能是字符溢出
【发布时间】:2012-02-03 17:26:52
【问题描述】:

我是编程新手,有时甚至我写的东西对我来说仍然很神秘。这是我第一次在网上寻求帮助。

我这里有一个问题,我已经有一段时间没能解决它了。

这就是我想做的:
从文件中逐字节读取到向量中,修改字节并将它们写回。

会发生这种情况:
所有加密的东西似乎都可以工作,但不知何故,经过几次这些操作后,文件的一部分丢失了。

在字节修改过程中我使用 char 溢出,这意味着我在向量的每个部分添加一些随机数并将其作为一个整体写回。

在我看来,这可能是某种我不知道的算术溢出问题。

顺便说一句,我使用 Qt SDK 和 Windows 环境,以防万一。

代码片段如下:

void crypt(string * password,string filename, int sign){
    vector<char> stack;
    ifstream is;
    is.open(filename.c_str());
    char c;
    for (int i = 0; !is.eof(); i++){
        is >> noskipws >> c;
        stack.push_back(c);
    }
    stack.pop_back();
    is.close();
    int code = 0;
    double x;
    char method = 0;
    int var;
    for (int i = 0; i < password->size(); i++)
        code += password->at(i);
    for (int i = 0; i < (stack.size()); i++){
        // some unrelated stuff skipped
        if (sign == 1)code += stack[i];
        stack[i] += var*method*sign;    //<----this might be the cause!
        if (sign == -1)code += stack[i];
        method = 0;
    }
    ofstream os;
    os.open(filename.c_str());
    for (int i = 0; i < stack.size(); i++){
        os << noskipws << stack[i];
    }
    os.flush();
    os.close();
}

对不起,代码中的混乱,我写它是为了测试。

任何想法都会受到赞赏。

【问题讨论】:

    标签: c++ encryption vector char overflow


    【解决方案1】:

    您正在以“文本”模式打开文件,这可能会导致问题,尤其是因为您的输出字符肯定会超出可打印的 ASCII 字符范围。这可能会导致问题,例如在 Windows 上,当您尝试输出值 0xD(回车)时,库会将其转换为 0xD,后跟 0XA(换行)。

    所以,尝试像这样以二进制模式打开文件:

    os.open(filename.c_str(), ios::binary);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多