linux 환경에서 c언어로 나 이외에 접속자 구분하는 프로그램 만들었는대 strcmp 반환 값이 좀 이상 합니다.

ehaakdl의 이미지

/*
check값이 초기화할떄는 0이지만 그 이후부터는 10,17값을 유지함 이상하다.
*/

#include
#include
#include
#include
#include

void error_info(char *message)
{
printf("%s\n",message);
}

int main()
{
char command[]="who";
char buff[1024]={0,};
FILE *file=NULL;
int check=0;
char *ptr=NULL;
char tok[]=" ";
char chan[1024] ="mose";
/*
printf("check:%d 이 아이디 이외는 다 침입자:",check);
scanf("%s",&chan);
*/
file=popen(command,"r");
if(file==NULL)
error_info("file popen error");

while(fgets(buff,sizeof(buff),file)!=NULL)
{
printf("check:%d ",check);

ptr = strtok(buff,tok);
printf("ptr:%s ",ptr);
printf(" chan: %s %d",chan,check);
check=strcmp(ptr,"change");
printf("\n");
/*if(check != 0)
{
printf("---------------------------------\n");
printf("비정상:%s\n", ptr);
while(ptr != NULL)
{
printf("기록:%s\n",ptr);
ptr=strtok(buff,tok);
}
printf("---------------------------------\n");



}*/

}
if(check == 0)
printf("안전\n");

pclose(file);
return 0;
}

shint의 이미지

http://www.cplusplus.com/reference/cstring/strcmp/

return value indicates
<0 the first character that does not match has a lower value in ptr1 than in ptr2
<0일 경우. 첫번째 문자는 ptr2보다 ptr1이 더 작은값을 가지며. 일치하지 않는다.

0 the contents of both strings are equal
0 두 문자열의 내용은 동일하다

>0 the first character that does not match has a greater value in ptr1 than in ptr2
>0일 경우. 첫번째 문자는 ptr2보다 ptr1 이 더 큰값을 가지며. 일치하지 않는다.

아래코드는 윈도우XP 홈. DevC++에서 확인한 내용입니다.

http://codepad.org/

#include <stdio.h>
#include <string.h>
 
 
void error_info(char *message)
{
    printf("%s\n",message);
}
 
 
int main(int argc, char** argv)
{
 
    int n;
    n = strcmp("1", "0");
    if(n >  0)    {   printf("n > 0\n");   }
    if(n == 0)    {   printf("n ==0\n");   }
    if(n <  0)    {   printf("n < 0\n");   }
    printf("n > 0\n");
 
 
 
    n = strcmp("ㄱ", "ㄴ");
    if(n >  0)    {   printf("n > 0\n");   }
    if(n == 0)    {   printf("n ==0\n");   }
    if(n <  0)    {   printf("n < 0\n");   }
    printf("n < 0\n");
 
 
    return 0;
}

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

익명 사용자의 이미지

반환값에 대해선 아는대 제가 같은 문자열을 비교 했는대도 반환이 0이 아닌값으로 나옵니다

shint의 이미지

리눅스 지역설정. 언어설정. 파일이름등에서 euc-kr과 utf-8 혹은 unicode 등에 문자도 확인해보셔야 할거 같습니다.

fgets()를 사용하는 경우. \n 값이 함께 얻어져서 이와 같은 현상이 발생했나봅니다.

\r\n 도 확인해야 할겁니다.

pclose( fp); 를 해주셔야 합니다.

http://kldp.org/node/140681 이분도 비슷한 어려움이 있네요.

아래 소스는. 32비트 윈도우XP에서 cygwin으로 확인한 내용입니다.

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
 
 
#define  BUFF_SIZE   1024
 
int fn_strcmp2( void)
{
    char  buff[BUFF_SIZE];
    FILE *fp;
 
 
    //ls 명령어의 출력 결과를 얻기 위해서. FILE 포인터를 얻는다.
    fp = popen( "ls", "r");
    if ( NULL == fp)
    {
        perror( "popen() 실패");
        return -1;
    }
 
    //값이 있을 동안. fgets()로 buff 에 값을 얻는다.
    while( fgets( buff, BUFF_SIZE, fp) )
    {
        int check=0;
        char *ptr=NULL;
 
        //buff에 " "로 구분된 데이터를 얻는다.
        ptr = strtok(buff," ");
        if(ptr == NULL)
        {
                continue;
        }
 
        //코드가 잘못될 수 있으니. 모든 값을 확인해주시기 바랍니다.
        //문자열의 마지막 값이 줄바꿈이라면. \0 으로 문장의 끝을 지정해준다.
        int len = strlen(ptr)-1;
        if( ptr[len] == '\n' )
        {
            ptr[len] = '\0';
        }
        printf("[FIRST] ptr:%s\t\t",ptr);
 
        //문자열을 비교합니다.
        check=strcmp(ptr,"test.txt");
 
        //비교결과를 출력합니다. 같으면 0
        printf("check %d\t\t", check);	
 
        //반복해서 값을 구분할 경우는. 첫번째 인자값으로 NULL 을 사용해야 합니다.
        ptr=strtok(NULL," ");
        printf("[NEXT] ptr:%s\n",ptr);
    }
 
    pclose( fp);
 
    return 0;
}
 
 
int main(int argc, char** argv)
{
    fn_strcmp2();
 
 
    return 0;
}
 
 
 
 
/*
g++ -o strcmp2.exe strcmp2.cpp
 
shint@shint-note ~
$ ./strcmp2
[FIRST] ptr:a           check -19               [NEXT] ptr:(null)
[FIRST] ptr:c.cpp               check -17               [NEXT] ptr:(null)
[FIRST] ptr:c.exe               check -17               [NEXT] ptr:(null)
[FIRST] ptr:f.cpp               check -14               [NEXT] ptr:(null)
[FIRST] ptr:f.exe               check -14               [NEXT] ptr:(null)
[FIRST] ptr:f.exe.stackdump             check -14               [NEXT] ptr:(null)
[FIRST] ptr:myfile.txt          check -7                [NEXT] ptr:(null)
[FIRST] ptr:s.cpp               check -1                [NEXT] ptr:(null)
[FIRST] ptr:s.exe               check -1                [NEXT] ptr:(null)
[FIRST] ptr:s.exe.stackdump             check -1                [NEXT] ptr:(null)
[FIRST] ptr:somefile.txt                check -1                [NEXT] ptr:(null)
[FIRST] ptr:strcmp.cpp          check -1                [NEXT] ptr:(null)
[FIRST] ptr:strcmp.exe          check -1                [NEXT] ptr:(null)
[FIRST] ptr:strcmp2.cpp         check -1                [NEXT] ptr:(null)
[FIRST] ptr:strcmp2.exe         check -1                [NEXT] ptr:(null)
[FIRST] ptr:tags                check -4                [NEXT] ptr:(null)
[FIRST] ptr:test.txt            check 0         [NEXT] ptr:(null)
[FIRST] ptr:who.txt             check 3         [NEXT] ptr:(null)
 
 
*/
댓글 첨부 파일: 
첨부파일 크기
Package icon test strcmp()와 strtok() 사용방법.zip39.65 KB

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.