【问题标题】:Binary files with Struct, classes, fstream error带有结构、类、fstream 错误的二进制文件
【发布时间】:2014-02-06 07:41:11
【问题描述】:

我有一个关于我的任务的问题。

这里我有两个类,员工类和通用类

void GM::addEmployee(fstream& afile, int noOfRecords)
{
    afile.open("EmployeeInfo.dat", ios::in | ios::binary);   
        employee::eInfo e;
        employee emp;
    char name[80];
    cout << "\nAdd Employee Info" << endl;
    cout << "---------------------" << endl;
    cout << "New Employee Username: ";
        cin.clear();
        cin.ignore(100, '\n');
    cin.getline(name, 80);
        //Check if there is already an entry inside the file with this name.
        //If yes, add fail
    bool flag = true;
    if(noOfRecords > 0)
    {
        for(int i=1; i<=noOfRecords; i++)
        {   
            afile.read (reinterpret_cast <char *>(&e), sizeof(e));
            if(!strcmp(name, e.username))
            {
                cout << "Username is used, add GM failed" << endl;
                flag = false;
            }
        }

    } 
    afile.close();

        if(flag)
        {
             //open in appending mode
             afile.open("EmployeeInfo.dat", ios::out | ios::app | ios::binary);
             strcpy(e.username, name);
             cout << "Please Enter New Employee's Password: ";
             cin.getline(e.password, 80);
             cout << "\nPlease Enter New Employee's Appointment "
                  << "\n(0 = GM / 1 = HM / "
                  << "2= BS / 3 = FOS)\n : ";
             cin >> e.eid;
             cin.clear();
             cin.ignore(100, '\n');
             emp.dist = strlen(e.password);
             emp.caesar_encrypt(e.password, 3, emp.dist);
             afile.write(reinterpret_cast <const char *>(&e), sizeof(e));
         afile.close();

             cout << "\nEmployee Added" << endl;
        }

}

以上是我的GM类的一个函数,就是添加员工。

我已将员工类中的结构声明为

struct eInfo
{
    char username [80];
    char password [80];
    int eid;
}; 

这种做法的问题在于,当我尝试添加员工时 我的 EmployeeInfo.dat 数据消失了。使用添加员工功能后,所有内容都变为空白。

谁能指导我做错了什么?

【问题讨论】:

    标签: c++ function class struct fstream


    【解决方案1】:

    这是将数据读入e的错误方式:

    afile.read(reinterpret_cast<char*>(&e), sizeof(e));
    

    同样,这是从e写入数据的错误方式:

    afile.write(reinterpret_cast<const char*>(&e), sizeof(e));
    

    如果您需要打印或读取e 的数据成员,您需要一次执行一个。此外,在这种情况下使用read/write 是不必要的,因为您只需使用提取器和插入器:

    afile >> e.username;
    // ...
    afile << e.username << e.password;
    

    【讨论】:

    • 我不精通C,但是有必要将afile对象传递给这个函数吗?
    • @bf2020 是否需要将afile 传递给what函数?抱歉,我似乎没有关注...顺便说一句,这是 C++
    • 别担心,是我没有关注……我的问题很糟糕。我不知道 C++ 并且对第一行使用的 :: 感到困惑。我会仔细阅读的。
    • @bf2020 哦,现在我明白你在说什么了——:: 是范围解析运算符。我们在此上下文中使用它来定义来自 GM 类的名为 addEmployee 的方法。 afile 是传递给函数的文件流对象。从某种意义上说,它是必要的,因为我们需要它来写入和读取文件。假设,我们可以在函数定义中创建文件流对象,但这会将addEmoloyee 方法限制为仅读取/写入特定文件。很高兴让函数的调用者选择他们想要传递的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多