Input Argument Examples

Filename given on command line, file is opened from program

   #include <fstream>
   #include <iostream>
   using namespace std;

   int main (int argc, char **argv) {
      for (int i=0 ; i < argc ; i++) cout << argv[i] << "\n";
      fstream fin;
      fin.open(argv[1], ios::in);
      if (fin.fail()) { cout << "help\n"; }
   }

Print any numbers that show up on the command line

   #include <iostream>
   using namespace std;

   int main (int argc, char **argv) {
      for (int i=1 ; i < argc ; i++) {
         if (atoi(argv[i]) != 0)
            cout << atoi(argv[i])+1 << "\n";
         else
            cout << "----\n";
      }
   }

Getting the environment, not from main's argument list, and an environment variable from the command line, and returning the value of that variable.

   #include <iostream>
   #include <stdio.h>
   using namespace std;

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

      if (argc != 2) {
         cerr << "Usage: " << argv[0] << " \n";
         exit(0);
      }
      p = getenv(argv[1]);
      if (p == NULL) cout << "Not There\n";
      else
         cout << "The value of " << argv[1] << " is " << p << "\n";
   } 

Changing the value of an environment variable given on the command line.

   #include <iostream>
   #include <stdlib.h>
   using namespace std;

   int main(int argc, char **argv) {
      char *p;
      if (argc != 3) {
         cerr << "Usage: " << argv[0] << "  \n";
         exit(0);
      }
      putenv(argv[1]);
      p = getenv(argv[2]);
      cout << argv[2] << " = " << p << "\n";
   }

Checking if a font is in the 'path'.

   #include <iostream>
   #include <stdio.h>
   #include <stdlib.h>
   using namespace std;

   int main(int argc, char **argv) {
      char *p; char *font_file="/ecrm1000.600pk"; char ptr[100];
      int i=0;

      p = getenv("PATH");
      if (p == NULL) {  
         cerr << "No such path\n";
      } else {
         while (*p != 0) {
            if (*p == ':') { 
               cout << ptr << font_file << "\n";
               i=0; 
               p++;
            } else { 
               ptr[i++] = *p++; 
               ptr[i] = 0; 
            }
         }
      }
      cout << ptr << font_file << "\n";
   } 

Add a variable to the environment.

   #include <iostream>
   using namespace std;

   extern char **environ;

   int main(int argc, char **argv) {  
      int i=0; char *p = "hello=1";

      while (environ[i] != 0) cout << environ[i++] << "\n";
      environ[i] = p;
      int save = i;
      cout << "-=- -=- -=- -=- -=- -=- -=-\n";
      for (i=0 ; i <= save ; i++) cout << environ[i] << "\n";
   }