SPFort SPFort - 19 days ago 6
C Question

While reading through the password file, the program never encounters EOF

Part of the program that I'm currently writing needs to check whether or not a user exists (this is for a unix system). However, while reading through the password file for users, EOF is never reached, therefore creating an endless loop. What could I be doing wrong?

int readPass;

int userExists = 0; // 0 means user doesn't exist, 1 means they do

// open password file to read in usernames
int passFD = open("/etc/passwd", O_RDONLY);

// open password file to read character by character
FILE* pass = fopen("/etc/passwd", "r");

// c-string to store usernames
char passUser[100];

// read through the password file
while (readPass != EOF)
{
int numPass = 0;

// read until reaching a colon, this is the username of the current line
while (readPass != ':')
{
readPass = fgetc(pass);
numPass += 1;
}
// store username is a c-string
read(passFD, passUser, numPass);
passUser[numPass - 1] = '\0';

// if the user exists, stop checking
if ((strcmp(passUser, argv[user])) == 0)
{
userExists = 1;
break;
}

// read junk until next line
readPass = NULL;
int junksRead = 0;
char passJunk[100];
while (junksRead < 6)
{
numPass = 0;
readPass = NULL;
while (readPass != ':' && readPass != '\n' && readPass != EOF)
{
readPass = fgetc(pass);
numPass += 1;
//printf("%c\n", readPass);
}
read(passFD, passJunk, numPass);
junksRead += 1;
}
}

// if the user doesn't exist, end the program
if (userExists == 0)
{
printf("%s does not exist\n", argv[user]);
return 0;
}`

Answer

You're probably getting stuck in one of the other while loops. Make sure each while loop is checking for EOF, particularly:

while (readPass != ':' && readPass != EOF)
            {
                readPass = fgetc(pass);
                numPass += 1;
            }
Comments