首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >校验和、数据完整性

校验和、数据完整性
EN

Stack Overflow用户
提问于 2015-11-19 02:50:23
回答 1查看 1.1K关注 0票数 0

此分配的伪代码是必要的: 1.以二进制模式打开指定的文件。2.将文件名保存在fileNames数组中。3.使用seekg和tellg 4确定文件大小。在一条语句5中将文件内容读入字符数组。关闭文件6。通过数组循环一次一个字符,并累积每个字节7的和,并将和存储到checkSums数组中。

代码语言:javascript
复制
#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“这样的值,我不知道如何解决这个问题。任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

发布于 2015-11-19 03:01:43

  1. 您正在堆栈上创建一个数组,而不对其内容进行归零,因此Arr将包含“垃圾”数据。
  2. 您正在创建大小固定的缓冲区,这意味着如果文件小于100,000字节,并且不能处理大于100,000字节的文件(不重用缓冲区),这意味着您在浪费空间。
  3. 如果文件小于100,000字节,则迭代缓冲区中的每个字节,而不是那些表示文件的字节。
  4. 我还注意到,您正在混合C和C++字符串函数。如果使用的是strcmp,则不需要调用C的string,然后使用string::compare
  5. C++不需要局部变量的前向声明,如果只在使用局部变量时声明局部变量,而不是一次性声明局部变量,代码将更加简洁。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33794412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档