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

Cancel that I've figured this one out. For anyone interested in the solution here it is:

USERPASS getUserPass(FILE *pUserFile, FILE *pPassFile)
{
	USERPASS user;
	char cBuffer[BUFFER_SIZE];
	int len;

	if (fgets(cBuffer,BUFFER_SIZE,pUserFile) != NULL)
	{
		//Override fgets
		len = strlen(cBuffer);
		fseek(pUserFile,-len,SEEK_CUR);

		stripNewline(cBuffer);
		user.name = calloc(strlen(cBuffer), sizeof(char));
		strcpy(user.name,cBuffer);

		if (fgets(cBuffer,BUFFER_SIZE,pPassFile) != NULL)
		{
			stripNewline(cBuffer);
			user.pass = calloc(strlen(cBuffer), sizeof(char));
			strcpy(user.pass,cBuffer);

			if(fgetc(pPassFile) == EOF)
			{
				rewind(pPassFile);
				fseek(pUserFile,len,SEEK_CUR);
			} else {
				fseek(pPassFile,-1,SEEK_CUR);
			}

		} else {
			user.name = NULL;
			user.pass = NULL;
		}
	} else {
		user.name = NULL;
		user.pass = NULL;
	}

	return user;
}

As you can see replacing that ELSE statement with a fgetc to check for the EOF, means the file pointers are moved in the previous execution of the function. The NULL assignments remain in case the file pointed to by pPassFile is empty.

This article has been dead for over six months. Start a new discussion instead.