I'm in the middle of writing a program where I want to use a single function to grab a Username from one file and a Password from another file. The idea is to pass the file pointers to the function so that each time the function is called it returns an new User/Password combination, the end result needs to be that each username is paired with each password. This is then returned as a struct.
However I'm having some problems getting this to work the way I want it to, at the end of the password file the function does not update the password field resulting in two calls giving the same user/password combination.
If anyone could offer any advice to the restructuring of this function to overcome this problem it would be greatly appreciated.
typedef struct {
char *name;
char *pass;
}USERPASS;
USERPASS getUserPass(FILE *pUserFile, FILE *pPassFile)
{
USERPASS user;
char cUserBuffer[BUFFER_SIZE];
char cPassBuffer[BUFFER_SIZE];
int len;
if (fgets(cUserBuffer,BUFFER_SIZE - 1,pUserFile) != NULL)
{
//Override fgets
len = strlen(cUserBuffer);
fseek(pUserFile,-len,SEEK_CUR);
stripNewline(cUserBuffer);
user.name = calloc(strlen(cUserBuffer), sizeof(char));
strcpy(user.name,cUserBuffer);
if (fgets(cPassBuffer,BUFFER_SIZE - 1,pPassFile) != NULL)
{
stripNewline(cPassBuffer);
user.pass = calloc(strlen(cPassBuffer), sizeof(char));
strcpy(user.pass,cPassBuffer);
} else {
//If there are no more passwords then the Password pointer is reset
//and the User pointer is moved forward.
//Unfortunately when this happens user.pass and user.name is not updated!
rewind(pPassFile);
fseek(pUserFile,len,SEEK_CUR);
}
} else {
user.name = NULL;
user.pass = NULL;
}
return user;
}