Linux 암호 파일을 명령 줄 인수에서 제공 한 사용자 이름으로 시작하는 줄을 검색하여 검사하는 간단한 C 프로그램을 만들려고합니다. 각 행은 콜론으로 구분 된 여러 개의 토큰으로 구성됩니다. 첫 번째 토큰은 사용자 이름이고, 두 번째는 관련이 없으며, 세 번째는 인쇄해야하는 사용자 ID (UID) 번호이고 네 번째 토큰은 인쇄해야하는 그룹 ID 번호 (GID)입니다.strtok() 및 strcmp()를 사용한 세그먼트 오류 오류
몇 가지 인쇄 테스트를 사용하고 솔루션을 온라인으로 검색 할 때, 내 토큰 변수를 NULL로 남겨 두었다고 생각합니다.이 시점에서 토큰의 printf는 아무 것도 인쇄하지 않습니다. 그런 다음 NULL 토큰은 strcmp를 사용하여 세그먼트 화 오류 오류를 생성하는 사용자 이름과 비교됩니다. 지금까지의 분석이 정확하다면 (C 언어를 처음 접한 이래로 잘되지 않았을 수도 있습니다.) 어떻게이 문제를 피하거나 수정할 수 있습니까? 왜 이런 일이 발생합니까?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *pwfile;
char *userName;
char buf[1024];
const char s[2] = ":";
char *token;
int ch, number_of_lines = 0;
int i;
if(argc != 2)
{
perror("must supply a user name");
return -1;
}
pwfile = fopen("/home/c2467/passwd", "r");
if(pwfile == NULL)
{
perror("error opening password file");
return -1;
}
userName = argv[1];
do//loop to determine number of lines in the file
{
ch = fgetc(pwfile);
if(ch == '\n')
number_of_lines++;
} while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
{
number_of_lines++;
}
for (i = 0; i <= number_of_lines; i++)//iterates through lines of file
{
fgets(buf, 1024, pwfile);//stores line into buf
if (ferror(pwfile) != 0)//tests error indicator for given stream
{
perror("fgets error");
return 1;
}
if (feof(pwfile) == 0)//checks if at end of file
{
break;
}
token = strtok(buf, s);//stores first token of current line in file
if(strcmp(token, userName) == 0)//compares token to user name entered
{
token = strtok(NULL, s);//Jumps to 2nd token in line, which is irrelevant so do nothing
token = strtok(NULL, s);//Jumps to 3rd token which is UID number
printf("UID: %s\n", token);
token = strtok(NULL, s);//Jumps to 4th token which is GID number
printf("GID: %s\n", token);
break;
}
}
fclose(pwfile);
return 0;
}
for 루프에서 i는 1부터 시작해야하거나 조건을 i
Knight71
그 C, 1부터 시작 어리 석다 –
만큼 논리적으로 나는 상관 없어 :) – Knight71