Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Simple way to check command line arguments in a C program

A simple way to check command line arguments.

Author: Joana Matos Fonseca da Trindade
Date: 2008.02.25

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

/* minimum required number of parameters */
#define MIN_REQUIRED 2

/* display usage */
int help() {
   printf("Usage: myprogram [-s <arg0>] [-n <arg1>] [-true]\n");
   printf("\t-s: a string a\n");
   printf("\t-n: a number\n");
   printf("\t-true: a single parameter\n");

   return 1;
}

/* main */
int main(int argc, char *argv[]) {
   if (argc < MIN_REQUIRED) {
      return help();
   }
   int i;

   /* iterate over all arguments */
   for (i = 1; i < (argc - 1); i++) {
       if (strcmp("-s", argv[i]) == 0) {
          /* do something with it */ 
          printf("string = %s\n", argv[++i]);
          continue;
       }
       if (strcmp("-n", argv[i]) == 0) {
          /* do something with it. for example, convert it to an integer */
          printf("number = %i\n", atoi(argv[++i]));
          continue;
       }
       if (strcmp("-true", argv[i]) == 0) {
          printf("true activated\n");
          continue;
       }
       return help();
   }
   return 0;
}

basic batch conditional evaluation

// check if argument has been passed to batch file

if not [%1]==[] echo %1
if not [%1]'==' echo %1

Python keyword arguments

This is something I always forget how to do, and it's kind of hard to Google or search the Python docs because you can't search for **.

The point is, when using **kwargs, you have to use the ** prefix not only in the function definition, but also in the call, prefixed to the variable you want to use as a keyword dictionary.

>>> d = dict(zip(list('123'),list('abc')))
>>> d
{'1': 'a', '3': 'c', '2': 'b'}
>>> def printkwargs(**kwargs):
...  for k,v in kwargs.items(): print k,v
...
>>> printkwargs(**d)
1 a
3 c
2 b
>>> printkwargs(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: printkwargs() takes exactly 0 arguments (1 given)

>>> # you have to tell python that you want the argument to be treated as a keyword dictionary by prefixing it with **
>>> # more info at http://mail.python.org/pipermail/python-list/2006-March/332182.html
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS