0

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;
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by just4why
0

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;
}

Edited by Ancient Dragon: n/a

0

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?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.