alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

【413】C 语言 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

 

posted on   McDelfino  阅读(571)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2018-06-23 【327】Python 中 PIL 实现图像缩放
2018-06-23 【326】PIL 截图及图片识别
点击右上角即可分享
微信分享提示