我是学生,我无法弄清楚如何完成这项任务。基本上应该自动计算数据文件的校验和,并将该校验和存储在unsigned int数组中。该文件的名称应该存储在另一个并行数组中,并且该文件的内容将被读入char数组以计算校验和。
这是我到目前为止所做的:
#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");
}
我们的输出应该是什么的例子(&#39; a&#39;是用户输入):
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
a
Specify the file path: c:\temp\tmp1
File checksum = 1530
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
更新:我现在整理了程序的第一部分,检查总和。我现在遇到的问题是如果在菜单上选择B,则输出正确。 它应该检查两个数组,并确保名称是正确的,并确保校验和是相同的,但我完全失去了如何将其放入代码。
答案 0 :(得分:0)
将您的代码更改为通过char从文件char中读取。 文件长度未知。 这样做直到文件结束:
inFile.seekg(0, ios_base::end);
int fileLen = inFile.tellg();
inFile.seekg(0, ios_base::beg);
for(int i =0; i<fileLen; i++)
{
char Arr[1];
inFile.read(Arr, 1);
sum += Arr[0];
}
inFile.close();
//总和是你的答案
答案 1 :(得分:0)
问题是for
循环的限制。无论文件的长度如何,您都可以阅读100000
次。将100000
更改为fileLen
会将对读取的每个字符的读取限制为Arr
:
for (i = 0; i < fileLen; i++) {
sum += Arr[i];
}
<强>输出:强>
$ ./bin/cscpp
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
a
Specify the file path:
tmpkernel315.txt
File checksum = 46173