- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <ctype.h>
- #include <unistd.h>
- void show_help();
- void show_version();
- int main(int argc, char *argv[])
- {
- char ch_type[4];
- char request_type[4];
- /* type[0] numbers
- type[1] lower case letters
- type[2] upper case letters
- type[3] special symbols */
- int option = 0;
- int len = 6; /* default length is 6 */
- *(int *)request_type = 0;
- while( (option=getopt(argc, argv, "aAhl:nsv")) != -1 ) {
- switch( option ) {
- case 'a':
- request_type[1] = 1;
- break;
- case 'A':
- request_type[2] = 1;
- break;
- case 'n':
- request_type[0] = 1;
- break;
- case 's':
- request_type[3] = 1;
- break;
- case 'h':
- show_help();
- return 0;
- case 'v':
- show_version();
- return 0;
- case 'l':
- if( (len=atoi(optarg)) < 0 ) {
- fprintf( stderr, "Illegal string length [%s].\\n", optarg );
- return -1;
- }
- break;
- case '?':
- show_help();
- return -2;
- default:
- abort();
- }
- }
- if( len > 255 || len < 1 ) {
- fprintf( stdout, "The length of string should be between 1 and 255.\\n" );
- return -1;
- }
- /* initialize random seed: */
- srand( time(NULL) );
- if( !*(int *)request_type || *(int *)request_type == 16843009 )
- while( len-- ) putchar( rand() % 93 + 33 );
- else
- while( len-- ) {
- option = rand() % 93 + 33; /* see the ascii table */
- *(int *)ch_type = 0;
- ch_type[0] = !!isdigit(option); /* if it is not zero, make it 1 */
- ch_type[1] = !!islower(option);
- ch_type[2] = !!isupper(option);
- if( !*(int *)ch_type ) /* it is NOT a number or letter. */
- ch_type[3] = 1;
- /* check if this character match our requirement */
- if( *(int *)ch_type & *(int *)request_type )
- putchar( option );
- else
- len++;
- }
- putchar( '\\n' );
- return 0;
- }
- void show_help()
- {
- fprintf( stdout, "Useage:\\n" );
- fprintf( stdout, "newp -aAnsl\\n" );
- fprintf( stdout, "-a\\t\\t the password contains lower case letters(a-z)\\n" );
- fprintf( stdout, "-A\\t\\t the password contains upper case letters(A-Z)\\n" );
- fprintf( stdout, "-n\\t\\t the password contains numerical character(0-9)\\n" );
- fprintf( stdout, "-s\\t\\t the password contains special symbols\\n" );
- fprintf( stdout, "-l length\\t set the password length(default: 6)\\n" );
- return;
- }
- void show_version()
- {
- fprintf( stdout, "Version: 1.0 %s\\n", __DATE__ );
- return;
- }
- //该片段来自于http://www.codesnippet.cn/detail/160720134616.html
来源: http://www.codesnippet.cn/detail/160720134616.html