Apr 24, 2015

[C/C++] command line arguments

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

int isStringDouble(char *s);


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

  if (argc == 1) {
    fputs("No arguments found.\n", stderr);
    exit(1);
  }


// to check if input argument is number
  if (isStringDouble(argv[1])) {
    double d = atof(argv[1]);       // to convert the argument into number (double)
    printf("Number argument found : %.3f\n", d);
  }
  else {
    fputs("Argument is not a number.\n", stderr);
  }

  return 0;
}

int isStringDouble(char *s) {
  int size = strlen(s);
  if (size == 0) return 0;     //  if "strlen" function returns 0, it is not a number.

  int i=0;
  for (i = 0; i < size; i++) {
      if (s[i] == '.' || s[i] == '-' || s[i] == '+') continue;
      if (s[i] < '0' || s[i] > '9') return 0;           // if the argument contains alphabet, it is not a number.
  }

  return 1;      // otherwise, the argument is a number.
}


---------------------------------------------------------------------------------

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    if ( argc != 2 ) // # of command line arguments should be 2 for correct execution (argv[0] = program filename, argv[1] = 1st command line argument)
    {
        printf( "usage: %s filename", argv[0] );     // print argv[0] (the program filename)
        char *fn = argv[1];
    }
    else
    {
        FILE *file = fopen( argv[1], "r" );     // assume argv[1] is a filename to open
      //or  FILE *file = fopen( fn, "r" ); 

        if ( file == 0 )        // fopen returns 0, the NULL pointer, on failure
        {
            printf( "Could not open file\n" );
        }
        else
        {
            int x;
// read one character at a time from file, stopping at EOF, which indicates the end of the file.  Note that the idiom of "assign to a variable, check the value" used below works because the assignment statement evaluates to the value assigned.
            while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
            fclose( file );
        }
    }
}


No comments:

Post a Comment