I would like to automatically generated staff number before generated the staff number i would like to check the staff.txt is the staff number exist. If exist then it will get the last's staff number and continue to adding. But the code that i creating it wont work. Please help to me rewrite.

void staff::setstaffid()
{
	int count = 0;

	ifstream instaffile("staff.txt", ios::in);

		if(!instaffile)
		{
			ofstream outstaffile("staff.txt", ios::out);
			outstaffile.close();

			ifstream instaffile("staff.txt", ios::in);
		}

		instaffile.read(reinterpret_cast<char *>(this), sizeof(staff));

		if(instaffile.eof())						//if the staff id is 0 then it will start from 20000
		{
			staffid = 1;
			return;
		}
		else
		{
			while(instaffile && !instaffile.eof())
			{
				count++;
				instaffile.read(reinterpret_cast<char *>(this),sizeof(staff));
			}
		}

		staffid = 1 + (count);					//increment the staff id

		instaffile.close();
		return;
}

Recommended Answers

All 2 Replies

line 17 is probably the wrong way to determine if the file is empty or not. What you should do is seek to end of file then get the file position.

instaffile.seekg(0, ios::end);
size_t sz = instaffile.tellg();
if( sz == 0)
{
    staffid = 1;
    return;
}

The loop at lines 24-28 is also wrong

instaffile.seekp(0, ios::beg); // go to beginning of tile
count = 0;
while( instaffile.read(reinterpret_cast<char *>(this),sizeof(staff))
{
     ++count;
}

The code that you give me is not working. It is other method to write the code again without read the file from staff.txt?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.