programing

명령줄에서 C 프로그램으로 인수 전달

mailnote 2023. 7. 25. 21:13
반응형

명령줄에서 C 프로그램으로 인수 전달

그래서 저는 리눅스에 있고 당신이 명령 줄에서 실행할 때 프로그램이 인수를 수락하도록 하고 싶습니다.

예를들면,

./myprogram 42 -b -s

그러면 프로그램은 42번을 int로 저장하고 -bor -s와 같은 인수에 따라 코드의 특정 부분을 실행합니다.

getopt를 사용할 수 있습니다.

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

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

C에서, 이것은 당신에게 전달된 인수를 사용하여 수행됩니다.main()함수:

int main(int argc, char *argv[])
{
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

본 기사에 대한 이 Arguments와 같은 자세한 내용은 온라인에서 확인할 수 있습니다.

사용을 고려해 보십시오.모든 조합에서 짧은 옵션과 긴 옵션을 모두 사용할 수 있습니다.

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

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

관련:

getopt 라이브러리를 보세요. 이것은 이런 종류의 것에 대한 거의 금본위제입니다.

대신에getopt()또한 사용을 고려할 수도 있습니다.argp_parse()(같은 라이브러리에 대한 대체 인터페이스).

libc 매뉴얼에서:

getopt보다 표준적이지만(단순 옵션 전용 버전은 POSIX 표준의 일부임),argp_parse매우 단순하고 매우 복잡한 옵션 구조 모두에서 더 많은 더러운 작업을 수행하기 때문에 더 쉽습니다.

하지만 저는 항상 기준에 만족했습니다.getopt.

N.B. GNUgetopt와 함께getopt_longGNU LGPL입니다.

다른 사람들은 이것의 머리를 때렸습니다.

  • 에 대한 일반적인 주장.main(int argc, char **argv)셸에서 명령행에 직접 액세스할 수 있습니다(명령줄이 손상되고 토큰화된 후).
  • 명령줄을 구문 분석할 수 있는 매우 표준적인 기능이 있습니다.getopt()그리고.getopt_long()

하지만 당신이 보았듯이, 그것들을 사용하는 코드는 약간 말이 많고, 꽤나 의미가 없습니다.저는 일반적으로 다음과 같은 것으로 그것을 시야 밖으로 밀어냅니다.

typedef
struct options_struct {
   int some_flag;
   int other_flage;
   char *use_file;
} opt_t;
/* Parses the command line and fills the options structure, 
 * returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);

그리고 가장 중요한 것은:

int main(int argc, char **argv){
   opt_t opts;
   if (parse_options(&opts,argc,argv)){
      ...
   } 
   ...
}

또는 C/UNIX에 대한 인수 구문 분석 도우미에서 제안한 솔루션 중 하나를 사용할 수 있습니다.

언급URL : https://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line

반응형