我是学生,无法弄清楚如何完成这项作业。基本上应该自动在数据文件上计算校验和,并将该校验和存储在无符号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");
}


还有一个我们的输出应该是什么的示例(“ a”是用户输入):

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,则输出正确。
应该检查两个数组并确保名称正确,并确保校验和相同,但是我完全不知道如何将其放入代码中。

最佳答案

问题是您的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

关于c++ - 卡在阵列上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27097904/

10-14 11:21