본문 바로가기
C 언어

C 언어에서 코맨드라인 인수

by treeCoder 2021. 7. 1.

C 언어에서 코맨드라인 인수를 사용하는 예제이다.

 

 

#include <stdio.h>

int main(int argc, char *argv[]) {

    while( --argc > 0 ) {

           printf("%s\n", argv[argc]);
           
    }

    return 0;
}

 

실행결과는 아래와 같다. 코맨드라인 인수가 역순으로 출력된다.

#include <stdio.h>

int main(int argc, char *argv[]) {

    while( --argc > 0 ) {

           printf("%s\n", *++argv);
           
    }

    return 0;
}

새로운 실행결과는 아래와 같다. 코맨드라인 인수가 정순으로 출력된다.

 

코맨드라인 인수를 한 줄로 나열하여 글대로 출력하는 프로그램을 만들어 보자.

#include <stdio.h>

int main(int argc, char *argv[]) { 

    int c;

    while( --argc > 0 ) {

           argv++;
           while( c = *argv[0]++ ) {
                   putchar( c );
           }
           putchar( ' ' ); // print space char 
    }

    return 0;
}

실행결과는 아래와 같다. 코맨드라인 인수가 한 줄로 연이어서 출력됨을 알수 있다.

 

 

마지막으로, 코맨드라인 인수를 문자열에 집어넣어서 출력하는 프로그램을 만들어 보자.

#include <stdio.h>
#include <stdlib.h>

#define MAX_STR 512

int main(int argc, char *argv[]) { 

    int c, i;
    char buf[ MAX_STR  ];

    i = 0;
    while( --argc > 0 ) {

           argv++;
           while( c = *argv[0]++ ) {
                   if( i++ < MAX_STR - 1) buf[i-1] = c;
                   else { puts("Memory not enough1"); exit(1); }
           }
           if( i++ < MAX_STR -1 ) buf[i-1] = ' '; // add space char 
           else { puts("Memory not enough2"); exit(1); }
    }
    if( --i < MAX_STR ) buf[i] = 0x00; // remove last space and finish string
    else { puts("Memory not enough3"); exit(1); }

    printf("[%s]\n", buf);

    return 0;
}

실행결과는 아래와 같다. 

댓글