CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Threaded View

  1. #1
    Join Date
    Mar 2005
    Posts
    40

    comparing objects from a binary file

    I have created a binary file with 30 locations (from 0 -> 29). It's supposed to store objects of this class:
    Code:
    class employee {
    private:
    	char name[25],telephone[15];
    	int room;
    public:
    	employee(char []="",char []="",int=0);
    	char *getname() { return name; }
    	char *gettelephone() { return telephone; }
    	int getroom() { return room; }
    	employee &setname(char n[]) { 
    		strcpy(name,n);
    		return *this;
    	}
    	employee &settelephone(char t[]) {
    		strcpy(telephone,t);
    		return *this;
    	}
    	employee &setroom(int r) {
    		room=r;
    		return *this;
    	}
    };
    
    employee::employee(char n[],char t[],int r) {
    	strcpy(name,n);
    	strcpy(telephone,t);
    	room=r;
    }
    Now, inside main I have this function being called:
    Code:
    void addEmployee(employee &em,fstream &df) {
    	employee em2;
    	int soem=sizeof(em);
    	char name[25],telephone[15];
    	int room;
    	cout<<"Enter the name of the employee.\n";
    	cin>>name;
    	cout<<"Enter the room of the employee.\n";
    	cin>>room;
    	cout<<"Enter the telephone number of the employee.\n";
    	cin>>telephone;
    	em.setname(name).setroom(room).settelephone(telephone);
    	bool wrote=false;
    	if (findEmployee(em,df) == -1) {
    		for (int i=0;i<30;i++) {
    			df.seekg(i*soem);
    			df.read(reinterpret_cast<char *>(&em2),soem);
    			if (em2.getroom()==0) {
    				wrote=true;
    				df.seekp(i*soem);
    				df.write(reinterpret_cast<const char *>(&em),soem);
    				break;
    			}
    		}
    		if (wrote)
    			cout<<"Succesfully added employee to database.\n\n";
    		else cout<<"Database is full.\n\n";
    	} else
    		cout<<"An Employee with those information already exists.\n\n";
    }
    and this is the findEmployee function:
    Code:
    int findEmployee(employee &em,fstream &df) {
    	int index=-1;
    	employee em2;
    	for (int i=0;i<30;i++) {
    		df.seekg(i*sizeof(em2));
    		df.read(reinterpret_cast<char *>(&em2),sizeof(em2));
    		if (strcmp(em2.getname(),em.getname()) == 0 && 
    strcmp(em2.gettelephone(),em.gettelephone()) == 0
    			&& em.getroom() == em2.getroom()) {
    			index=i;
    			break;
    		}
    	}
    	return index;
    }
    It seems to always say that the employee does not exist, even though I am entering the same data everytime. How can I compare objects froma binary file?
    Last edited by zifeer; January 20th, 2006 at 01:13 PM. Reason: code fixes

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured