c++校验和读取不存在换行符

C++ checksum reading nonexistent newline

本文关键字:换行符 不存在 读取 校验和 c++      更新时间:2023-10-16

我通过将输入文件读入字符数组,然后遍历该数组并将每个字符添加到校验和中,对文件进行非常基本的校验和。问题是,当我这样做时,我所有的校验和都是10太高(10是换行字符的ascii十进制值)。

它是如何换行字符被插入到我的代码,当我知道一个事实,没有换行字符在我的文本?即使是单行文本文件也会添加换行符!

#include <iostream>
#include <fstream>
int main () {
    int fileLength = 0;
    std::ifstream inputFile;
    char charArray[10000];
    int checkSumValue = 0;
    // open file in binary
    inputFile.open("/Path/To/File", std::ios::binary);
    // get file length, then return to beginning of file
    inputFile.seekg(0, std::ios_base::end);
    fileLength = inputFile.tellg();
    inputFile.seekg(0, std::ios_base::beg);
    // read all data from file into char array
    inputFile.read(charArray, fileLength);
    // iterate over char array, adding ascii decimal value to checksum
    for (int num = 0; num <= fileLength; num++) {
        std::cout << "Checksum value before iteration " << num << " is " 
        << checkSumValue << std::endl;
        checkSumValue += static_cast<int>(charArray[num]);
    }
    // properly close out the input file
    inputFile.close();
    inputFile.clear(std::ios_base::goodbit);  
    std::cout << "The checksum value is: " << checkSumValue << std::endl;
    std::cout << "The file length is: " << fileLength << std::endl;
    return 0;
}

你的问题在这里:

num <= fileLength

应该是:

num < fileLength
例如

。如果长度是1。那么唯一有效的字符是charArray[0]

也注意。这样做:

inputFile.read(charArray, fileLength);

是危险的,因为fileLength可能大于数组的大小。
一个更好的解决方案是使用一个向量(因为它是动态大小的)

std::vector<char>   charArray(fileLength);
inputFile.read(&charArray[0], fileLength);

但是你真的需要将数据复制到数组中吗?为什么不直接做这个加法呢

size_t checkSumValue = std::accumulate(std::istreambuf_iterator<char>(fileLength),
                                       std::istreambuf_iterator<char>(),
                                       size_t(0)
                                      );

Martin也是正确的-你应该(num <</p> 文件长度

另一种可能性是您在编辑器中创建了文件,它人为地为您添加了一个虚假的换行符。这是常见的。尝试将文件转储到十六进制编辑器中。我刚刚运行了你的程序(删除<=),它工作得很好。