如何在C中处理命令行参数?

时间:2012-12-07 16:24:18

标签: c testing input cmd output

我想知道如何通过命令行获取其他输入?我想查找“-w”和数字,所以它看起来像“-w60”和“-s”。此输入通过命令行给出,因此它看起来像这样:


c:\Users\Username\Desktop> wrapfile.exe -w5 -s test.txt

输出应如下所示:

Hello  
,  
this  
is a  
test

-w5和-s的意思是:

-w5 = width(一次只能显示5个字符)

-s = spacing(包括间距,尽可能多的整个单词)

我想创建一个扫描这两个字符的函数,如果有人知道如何格式化输出以便它做它需要做的事情,那也会有所帮助。

我只是有点困惑,我一直在研究这个程序,我只是想了解如何正确地扫描和使用这些东西。

这是我当前的代码,它从命令行接收无限量的文本文件:

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

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

    int l = 1;
    while(l != argc)
    {
        FILE *fp;    

        fp = fopen(argv[l], "rb");
        l++;

        if (fp != NULL) 
        {
        int i = 1;
        do
        {
            i = fgetc(fp);   
            printf("%c",i);
            printf(" ");
        }
        while(i!=-1);
        fclose(fp);
        }
        else
        {
        printf("Error.\n");
        }
    }
}

/*

void scanningForWS(int argc, char **argv)
{
}

*/

2 个答案:

答案 0 :(得分:2)

如果您将-w5 -s test.txt传递给您的计划,您的argv就是:

argv[0] = "wrapfile.exe" 
argv[1] = "-w5" 
argv[2] = "-s" 
argv[3] = "test.txt"

所以:

int l = 1;
fp = fopen(argv[l], "rb");

不是你想要的。

为了便于说明...为了打印到“限制”宽度,您可以执行以下操作:

char * h = "this is a string longer than width"; // you'd get this from your file
int width = argv[1][2] - '0'; // you wouldn't hardcode this...
int count;

for(count = 0; count < strlen(h); count++){
    if((count % width) < width - 1)
        printf("%c", str[count];
    else
        printf("%c\n", str[count];
}

答案 1 :(得分:0)

我发现getopt使用起来很麻烦。编写自己的测试并不太难。例如:

#include <string.h>
#include <stdio.h>

int main(int argc, char **argv) {
   int haveSpacing = 0;
   int haveWidth = 0;
   FILE *fp = 0;
   while (*++argv) {
      if (!strcmp(*argv, "-s")) { // check for -s switch
         haveSpacing = 1;
      }
      else if (sscanf(*argv, "-w%d", &haveWidth) == 1) { // check for -wxx
      }
      else if (**argv == '-') { // reject anything else beginning with "-"
         printf("invalid switch %s\n", *argv);
         return 1;
      }  
      else if (argv[1]) { // filenaname must be last arg, so arg[1] must be NULL
         printf("invalid arg %s\n", *argv);
         return 1;
      }
      else if (!(fp = fopen(*argv, "rb"))) { // open last arg, the filename
         perror(*argv);
         return 1;
      }
   }
   if (!fp) {
      printf("missing filename\n");
      return 1;
   }

   // ...
   return 0;
}