繁体   English   中英

0xC0000005 读取二进制文件时抛出异常(C++)

[英]0xC0000005 Exception thrown when reading binary file (C++)

我正在尝试让用户登录和注册系统使用二进制文件来保存数据,并检查用户名和密码是否与保存的相同。 Create_Login()Write()时,甚至在之后调用Login()时,它似乎工作正常。 Login()被自己调用时,就会出现问题。 尝试读取用户名和密码时抛出异常。 我一直在尝试解决这个问题一段时间,只是看不到它。 任何帮助,将不胜感激

这是我的代码

主文件

int input;
cin >> input;

    switch (input) {
    case 1:
        file.Login("");
        break;

    case 2:
        file.Create_Login();
        break;
}

.h 文件

struct Files {
    char username[50];
    char password[50];


    string CheckPassword;
    string CheckUsername;

public:
    void Write(string name);
    void Login(string name);
    void Create_Login();

    Files();
    ~Files();

public:

    ifstream ReadFile; // Read
    ofstream WriteFile; // Write
};

.cpp 文件

Files::Files() {}

void Files::Login(string name) {
    cout << "\nEnter Username: " << flush; cin >> CheckUsername;
    cout << "Enter Password: " << flush; cin >> CheckPassword;

    name = CheckUsername;
    ReadFile.open(name + ".bin", ios::out | ios::binary);

   cout << "Your Username is: " << CheckUsername << ", " << "Your Password is: " << CheckPassword << endl; // debug line

    if (ReadFile.is_open()) {
        cout << "Opened file " + name + ".bin" << endl;

        ReadFile.read(reinterpret_cast<char*>(&username), sizeof(Files)); //Execption Thrown Here!!!!!
        ReadFile.read(reinterpret_cast<char*>(&password), sizeof(Files));
    
        if (CheckUsername == username && CheckPassword == password) {
            cout << "Access Granted" << endl;
        }
        else if (CheckUsername != username && CheckPassword != password) {
            cout << "Access Denined" << endl;
        }
        else {
            cout << "Error!!!" << endl;
        }
    }
    else {
        cout << "Could not open file: " + name << endl;
        cout << "File does not exist" << endl;
    } 
}

void Files::Create_Login() {
    cout << "Create UserName >> " << flush; cin >> username;
    cout << "\nCreate Password >> " << flush; cin >> password;

    Write(username);
}

void Files::Write(string name) {
    WriteFile.open(name + ".bin", ios::binary);

    if (WriteFile.is_open()) {
        WriteFile.write(reinterpret_cast<char*>(&username), sizeof(Files));
        WriteFile.write(reinterpret_cast<char*>(&password), sizeof(Files));
        WriteFile.close();
    }
    else {
        cout << "could not create file: " << name + ".bin" << endl;
    }
    Login(username);
}

Files::~Files() {
    cout << "Destructor Called" << endl;
    ReadFile.close();
}

异常已解决。 通过改变

ReadFile.read(reinterpret_cast<char*>(&username), sizeof(Files)); 
ReadFile.read(reinterpret_cast<char*>(&password), sizeof(Files));
 

 ReadFile.read(reinterpret_cast<char*>(&username), sizeof(username)); 
 ReadFile.read(reinterpret_cast<char*>(&password), sizeof(password));

谢谢(你的)信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM