Linux C Programing

#include <iostream>
#include <stdlib.h>
#include <stdio.h> //printf
#include <unistd.h> //extern char **environ
using namespace std;

#include <vector>
#define _GNU_SOURCE

#include <getopt.h>

// THIS PROGRAM CAN ./program --env=HOME
// ./program -e HOME
// ./program --e HOME
// ./program -h
// ./program --h or ./program --help
extern char **environ;
int main(int argc,char *argv[])
{
    /*
    cout << "Hello, World!" << endl;
    char *v_char = "houdini";
    char *v_char_list[5]={"jack","luke"};

    cout << v_char<<endl;
    cout << v_char_list[0]<<endl;
    return 0;
     */

    /*
    char *v_char_list[] = {"jack","luke"};
    char **v_char_point = v_char_list;

    while(v_char_point!=NULL)
    {
        cout<<*v_char_point<<endl;
        v_char_point++;
    }
    */

    if (argc<=1)
    {
        printf("THIS IS A LINUX TOOLS BASED ON KATANA,PLEASE -h/--help SHOW TIPS
");
    }

    int opt;
    struct option longopts[] = {
            {"env",1,NULL,'e'},
            {"help",0,NULL,'h'},
            {"showenv",0,NULL,'s'},
            {0,0,0,0}
    };
    while ((opt=getopt_long(argc,argv,":e:h:s",longopts,NULL)) != -1 )
    {
        switch (opt) {
            case 'e':
            {
                printf("get new option: %s 
", optarg);
                char *env_name = getenv(optarg);
                if (env_name)
                {
                    printf("%s value is %s 
", optarg, env_name);
                }
                else
                {
                    printf("The %s env do not exist
", env_name);
                }
                break;
            }
            case 'h':
            {
                printf("33[40;37m -h/--help : This Program helps
 33[0m");
                printf("33[40;37m -e=value/--env=value : You want get the env value
 33[0m");
                printf("33[40;37m -s/--showenv : show current environment 
 33[0m");
                printf("
");
                break;
            }
            case 's':
            {
                char **env=environ;
                while(*env)
                {
                    printf("%s
",*env);
                    env++;
                }
                break;
            }
            case '?':
                printf("unkown option: %c 
",optopt);
                break;
        }
    };
    for(;optind<argc;optind++)
    {
        printf(" "%s" argument have no use...: 
",argv[optind]);
    }




    exit(12);
}
原文地址:https://www.cnblogs.com/gearslogy/p/5291836.html