413C 语言 Command line

Posted alex-bn-lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了413C 语言 Command line相关的知识,希望对你有一定的参考价值。

 

Command-Line Arguments

 

All the executable programs above have a main(void) program

  • more generally, executables take arguments on the command line
  • these enter the program via parameters
    切换行号显示
       1  int main(int argc, char *argv[])
    

For example:

prompt$ ./a.out -pre 3

 

means that:

  • argc refers to the number of arguments, including the program name

    • argc = 3

  • argv[] allows access to arguments represented as strings

    • argv[0] is a pointer to the string "./a.out"

    • argv[1] is a pointer to the string "-pre"

    • argv[2] is a pointer to the string "3"

 

Command-line argument processing example 1

 

Write a program that:

  • takes an optional numerical command-line argument 1, 2, 3 or 4
  • if the argument is not one of these characters (!), a usage message is printed
    切换行号显示
     // commarg.c
     #include <stdio.h>
     #include <stdlib.h>
     int main(int argc, char *argv[]) 
         if (argc == 1 ||
            (argc == 2 && atoi(argv[1]) >= 1 && atoi(argv[1]) <= 4)) 
             // we can do something here
          else 
             printf("Usage: %s [1|2|3|4]\n", argv[0]);
         
         return EXIT_SUCCESS;
     
    
  • notice that atoi() had to be called to convert the character to a number

  • compiling and executing the program:
     prompt$ dcc commarg.c
     prompt$ ./a.out
     prompt$ ./a.out 1
     prompt$ ./a.out 2
     prompt$ ./a.out 3
     prompt$ ./a.out 4
     prompt$ ./a.out 5
     Usage: ./a.out [1|2|3|4]

 

Command-line argument processing example 2

 

Write a program that:

  • takes an optional command-line switch -reverse

  • if the switch is not correct, a usage message is printed
    切换行号显示
     // commargrev.c
     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
     int main(int argc, char *argv[]) 
         if (argc == 1 ||
            (argc == 2 && !strcmp(argv[1], "-reverse"))) 
             // NOTE: strcmp returns 0 if matches.
             // we could do something here
          else 
             printf("Usage: %s [-reverse]\n", argv[0]);
         
         return EXIT_SUCCESS;
     
    
     prompt$ ./a.out
     prompt$ ./a.out -reverse
     prompt$ ./a.out rubbish
     Usage: ./a.out [-reverse]

 

Makefile

 

以上是关于413C 语言 Command line的主要内容,如果未能解决你的问题,请参考以下文章

编程语言和shell编程的基础内容以及grepegrep命令及相应的正则表达式和用法

python知识简单总结 - 语言基础

编程语言和shell编程的基础内容以及grepegrep命令及相应的正则表达式和用法

xcode上编译c语言程序报错:ld: x duplicate symbol for architecture x86_64 clang: error: linker command failed

xcode上编译c语言程序报错:ld: x duplicate symbol for architecture x86_64 clang: error: linker command failed

linux shell学习四