校验和,数据完整性
Checksums, Data Integrity
此赋值的伪代码本质上是:1.以二进制模式打开指定的文件2.将文件名保存在fileNames数组中。3.使用seekg和tellg确定文件大小4.在一条语句中将文件内容读取到字符数组中5.关闭文件6.循环遍历数组,每次一个字符,并累加每个字节的总和7.将总和存储到checkSums数组中。
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
//declare variables
string filePath;
void savefile();
char choice;
int i, a, b, sum;
sum = 0;
a = 0;
b = 0;
ifstream inFile;
//arrays
const int SUM_ARR_SZ = 100;
string fileNames[SUM_ARR_SZ];
unsigned int checkSums[SUM_ARR_SZ];
do {
cout << "Please select: " << endl;
cout << " A) Compute checksum of specified file" << endl;
cout << " B) Verify integrity of specified file" << endl;
cout << " Q) Quit" << endl;
cin >> choice;
if (choice == 'a' || choice == 'A')
{
//open file in binary mode
cout << "Specify the file path: " << endl;
cin >> filePath;
inFile.open(filePath.c_str(), ios::binary);
//save file name
fileNames[a] = filePath;
a++;
//use seekg and tellg to determine file size
char Arr[100000];
inFile.seekg(0, ios_base::end);
int fileLen = inFile.tellg();
inFile.seekg(0, ios_base::beg);
inFile.read(Arr, fileLen);
inFile.close();
for (i = 0; i < 100000; i++)
{
sum += Arr[i];
}
//store the sum into checkSums array
checkSums[b] = sum;
b++;
cout << " File checksum = " << sum << endl;
}
if (choice == 'b' || choice == 'B')
{
cout << "Specify the file path: " << endl;
cin >> filePath;
if (strcmp(filePath.c_str(), fileNames[a].c_str()) == 0)
{
}
}
} while (choice != 'q' && choice != 'Q');
system("pause");
}
我得到的值是"-540000",我不知道如何解决这个问题。非常感谢您的帮助!
- 您正在堆栈上创建一个数组,而不将其内容清零,因此
Arr
将包含"垃圾"数据 - 您正在创建具有固定大小的缓冲区,这意味着如果文件小于100000字节,并且无法处理大于100000字节的文件(如果不重用缓冲区),则会浪费空间
- 如果文件小于100000字节,则迭代缓冲区中的每个字节,而不是代表文件的那些字节
- 我还注意到您正在混合使用C和C++字符串函数。如果使用
string
,则不需要调用C的strcmp
,然后使用string::compare
- C++不需要局部变量的前向声明,如果在使用局部变量时只声明局部变量,而不是一次声明所有变量,那么代码会更干净
相关文章:
- 如何用尽可能少的数据将数据缓冲区计算为零校验和值
- 计算校验和的逐位运算符
- 如何从存储在 QByteArray 中的十六进制值计算校验和
- 如何在 c++ 中计算对象的哈希/校验和/指纹?
- C++文件传输的校验和算法
- 如何从 IP 校验和字段中计算十六进制值
- 计算句子的校验和(XOR)(由不同变量/类型的组合形成)
- 目录校验和
- 编译后如何计算某些二进制功能(或基本块)的校验和
- PMS5003带有ESP8266-许多校验和错误
- 未正确的校验和释放对象 - 打印时错误
- 将C++校验和函数转换为 Java
- 确定是否使用boost.asio计算UDP校验和
- 校验和CRC 16从C 到Java
- 不同的CRC32校验和同一文件
- Qt,tcp/ip通信校验和
- 正在计算ICMP数据包校验和
- 如何计算 dmg 文件上的主校验和和数据分叉校验和
- UDP标头校验和不正确时是否丢弃UDP数据包
- 校验和,数据完整性