首页 文章

将结构成员写入二进制文件并使用带有C的fstream读取它们

提问于
浏览
0

对于C世界来说还是新手,以下问题是因为家庭作业!我没有找到太多的帮助搜索以前回答的问题或谷歌,并不意味着我没有错过它 .

家庭作业的目标:1 . )获取用户输入信息并将其存储在二进制文件中 . 2.)稍后再读取该数据 .

我有一个最多10个结构的数组,struct接受用户名的char数组,用户电话号码的char数组和浮动工资 . 当我输入一些测试用例时,文件写入,我假设正确 . 当我去读取值时,第一个名称和第一个电话号码打印得很好 . 浮动给了我-4013602080无论我输入测试用例的 Value . 从那里开始走下坡路 . 我正在尝试这个 . My question boils down to two parts, am I "properly" writing the structure members to the file, and how do I read in floats from binary? (or should would it be advantageous to use fopen and fclose?) 提示或参考将是美好的 .

//my header
#ifndef USERS_H
#define USERS_H


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <limits>
#include <iomanip>

const int arsize=20;
using namespace std;
struct emp
{
    char name[arsize];
    char phone[arsize];
    float salary;
};
class Users
{
private:
    //const int arsize=20;
    int choice, num_of_names;
public:
    Users();
    void menu();
    void enter(emp*pt, int n);
    void print_all(emp*pt);
    void print_condition(emp*pt);
    void end_phone_array(emp*pt);
    void bubble_sort(emp*pt);
    void selection_sort(emp*pt);
    void raise(emp*pt);
            void file_store(emp*pt);
    void file_read(emp*pt);

};
#endif USERS_H_

以下是我认为源文件中的必要部分:

void Users::enter(emp*pt, int n)
{
    extern int gl,count,f;
    if(gl+n>10)
    {
        cout<<"Memory Full!\n";
    }
    else
    {
        for (int i=count;i<f+n;i++)
        {
            gl++;
            cout<<"Enter user #"<<i+1<< " name(no more than 20 characters)\n";
            cin.get();
            cin.getline(pt[i].name, arsize);//.get();
            cout<<"Enter user #"<<i+1<< " phone #\n";
            cin.getline(pt[i].phone, arsize);//.get();
            cout<<"Enter user #"<<i+1<< " salary\n";
            (cin>>pt[i].salary);//.get();
        }
        count=gl;
        f=gl;
    }
}
void Users::file_store(emp* pt)
{
    //ifstream::pos_type size;
    extern int gl;
    //float test;
    //ofstream Testfile ("C:\\Users\\Ian\\Desktop\\Programming\\C++\\data.bin", ios::out| ios::binary);  //for personal computer use
    ofstream Testfile ("data.bin", ios::out | ios::binary);
    for (int i=0; i<gl;i++)
    {
        Testfile.write((char*)&pt[i].name, sizeof(pt));
        Testfile.write(pt[i].phone, sizeof(pt[i].phone));
        Testfile.write((char *)&pt[i].salary, sizeof(pt[i].salary));
    }
}
void Users::file_read(emp*pt)
{
    //extern int gl;
    struct TEST
    {
        char n_array[20];
        char p_array[13];
        float salary;
    };
    TEST test[20];
    for (int i=0;i<20;i++)
    {
        test[i].n_array[0]='\0';
        test[i].p_array[0]='\0';
        test[i].salary=0.0;
    }
    /*ifstream::pos_type size;
     * char *memblocktest;*/
    ifstream test_in ("data.bin", ios::in | ios::binary);
    for(int i=0;i<10;i++)
    {
        if(test_in.is_open())for(int i=0;i<10;i++)
        {
            test_in.read((char*)&test, sizeof(test));
            cout<<test[i].n_array<<"\n";
            cout<<test[i].p_array<<endl;
            cout<<"$"<<test[i].salary<<endl;
        }
        else
            cout<<"Don't know what I am doing!\n";
    }


}

这是主文件

#include "stdafx.h"
#include "users.h"
#include <iostream>
#include <cctype>
#include <limits>
#include <iomanip>
#include <cstring>
using namespace std;


extern int gl=0, count =0, f=0;
int main()
{
    Users Test;
    std::cout.setf(std::ios::fixed);
    std::cout.precision(2);
    emp*test=new emp[10];
    Test.menu();
    int choice, num_of_names;
    while(1)
    {
        if(!(cin>>choice))
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
            cout<<"ERROR!\n";
        }
        else
            break;
    }
    while(choice!=9)
    {
        switch(choice)
        {
            case 1:{cout<<"How many users will you enter?\n";
                    cin>>num_of_names;
                    Test.enter(test, num_of_names);
                    Test.end_phone_array(test);
                    break;}
            case 2:{Test.print_all(test);
                    break;}
            case 3:{Test.print_condition(test);
                    break;}
            case 4:{Test.bubble_sort(test);
                    break;}
            case 5:{Test.selection_sort(test);
                    break;}
            case 6:{Test.raise(test);
                break;}
            case 7:{Test.file_store(test);
                    break;}
            case 8:{Test.file_read(test);
                break;}
            default:{"Bad Choice..........\n";
                     break;}
        }
        Test.menu();
        while(1)
        {
            if(!(cin>>choice))
            {
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(),'\n');
                cout<<"ERROR!\n";
            }
            else
                break;
        }
    }
    delete [] test;
    //system("Pause");
    return 0;
}

我想我可以改进很多东西,但是现在我想把二进制部分想出来 . 任何提示都非常感谢 . 谢谢!

1 回答

  • 3

    这看起来不对:

    void Users::file_store(emp* pt)
    {
        // etc...
    
            Testfile.write((char*)&pt[i].name, sizeof(pt));
            Testfile.write(pt[i].phone, sizeof(pt[i].phone));
            Testfile.write((char *)&pt[i].salary, sizeof(pt[i].salary));
    

    在第一行中,您使用 sizeof(pt) 作为大小,其中大小实际上是指针值的大小 . 您还将获取名称数组的地址( char** )并将其转换为 char*

    修理:

    Testfile.write(pt[i].name, sizeof(pt[i].name));
    Testfile.write(pt[i].phone, sizeof(pt[i].phone));
    Testfile.write((char *)&pt[i].salary, sizeof(pt[i].salary));
    

    实际上,您可能不需要单独执行这些字段(除非您尝试遵循与结构不同的顺序),因为该结构没有任何动态数据 . 您可以将整个记录存储在一个匹配中:

    Testfile.write((char*)&pt[i], sizeof(struct emp));
    

    更好的是,您可以将整个数组存储在一个命中并避免循环:

    Testfile.write((char*)pt, gl * sizeof(struct emp));
    

    同样适用于阅读...请注意,您可能还希望将 gl 的值存储在文件中,以便了解它包含的记录数 . 或者如果你想要稍微更加神秘,你可以检查文件大小并将 sizeof(struct emp) 分成它来推断记录的数量 .

相关问题