2014-10-24 2 views
0

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

for 루프에서 i는 1부터 시작해야하거나 조건을 i Knight71

+0

그 C, 1부터 시작 어리 석다 –

+0

만큼 논리적으로 나는 상관 없어 :) – Knight71

답변

1

파일을 처음부터 끝까지 읽으면 새 줄 수를 알 수 있습니다.

그러나 처음부터 다시 읽지 않고 다시 읽기 시작합니다. 이로 인해 fgets가 실패하게됩니다 (EOF 이후 읽음).

당신이 전화를해야 :

fseek(pwfile, 0 , SEEK_SET); 
당신은 또한 파일도 되감기 후, 의미 파일의 TEH 끝에 아니라고 경우 사실이다 (feof(pwfile) == 0)에의에서 휴식

, 첫 번째 줄을 처리하기 전에 중단됩니다.

if (feof(pwfile)) 

은 그렇지 않으면 좋은 제대로 작동하는 것 :

당신은 그가 변경해야합니다. (그러나 나는 개인적으로 strtok을 싫어한다.)

+1

감사합니다. 훌륭하게 작동합니다. – Paddyngton