Am I reading file and using map container correctly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int BuildUserPass(std::map<std::wstring, std::wstring>& userpass)
{
	wchar_t tempuser[15], temppass[15];
	
	std::wifstream userlistFile(L"userlist.txt");
	if ( userlistFile == NULL )
		return -1;
	
	while ( !userlistFile.eof() )
	{
		userlistFile.get(tempuser, 15, ' ');
		userlistFile.seekg(0, std::ios_base::cur);
		userlistFile.get(temppass, 15, '\n');

		if ( !userlistFile.eof() )
			userlistFile.seekg(0, std::ios_base::cur);
		
		userpass[tempuser] = temppass;
	}
	
	userlistFile.close();
	return 0;
}


This is for a personal project. Inside of userlist.txt I have a username, a space, and then the password to go along with that username. A newline denotes a new username/password combination. The above code works for me but I would really appreciate some advice on whether I'm doing that an efficient way or if there is a better way.

I also understand that during the addition to userlist.txt I must make sure a username does not exceed 15 characters and a password does not exceed 15 characters.

Any advice is greatly appreciated.

Thanks,
Mack
Last edited on
Lines 12, 15, and 16 are meaningless.
No because without line 12 the second userlistFile.get will get the space and then the password.

userlistFile.get(tempuser, 15, ' '); stops right at the space but doesn't go past it. my seekg call goes right past the space.

Same thing goes for the second get. If I take out line 15 the program loops forever and eof() is never reached for some reason.
Hmm... What happens if you change the 0 to a 1?
It sets the position 2 over so I lose a letter. I was kind of confused about that as well.

Hmm, should I use getline instead and do the parsing in memory so I can half the number of hard disk reads?
Last edited on
Input is very likely buffered, anyway. I think using std::getline() will be for the best, though.
I try to avoid messing around with the seekg method, it can behave weird/slow and when you use it you are assuming all the data is perfectly formatted in your file.

I personally would change the seekg calls to just use the ws stream modifier. This way, your program won't crash if the data has 2 spaces between the username and password by accident, or if there is a blank line between some of the data. It will all still work properly.

The other thing is, you should always check for .good() instead of !.eof()

Finally, by using .get() with a 15 char limit, you never report that there is a problem. It is just going to get the first 15 chars, then the next time it reads it will start in the same word and start reading, then stop at the space. So you'll end up with half words and mismatched username/password combos.
Last edited on
Thanks both of you. I really appreciate your time and advice =D
Topic archived. No new replies allowed.