私が現在書いているプログラムの一部は、ユーザが存在するかどうかをチェックする必要があります(これはUNIXシステム用です)。ただし、ユーザーのパスワードファイルを読み取っている間は、EOFには到達せず、無限ループを作成します。私は何が間違っていますか?パスワードファイルを読み取っている間、プログラムは決してEOFに遭遇しません
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;
}`
?そして、あなたは 'EOF'をチェックしていない内部ファイル読み取りループをいくつか持っています。コードは完全な混乱です。 –
これは何をすべきか: 'read(passFD、passUser、numPass);'?ところで:fgets()はあなたの友人です。 – wildplasser
私はそれをcharとして持っていて、それを変更するのを忘れていたので、NULLがそこにあります。また、すべてのループがEOFをチェックする必要はなく、行の最後まで読み取るループのみが必要です。たとえば、ユーザー名を読み取るとEOFには到達しないので、チェックするのは無意味です。 – SPFort