23,128
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#define DEFAULT_COMMENT_SIGN "#"
#define CONFIG_FILE "/etc/wifi/wpa.conf"
#define DEFAULT_IF "ctrl_interface=/var/run/wpa_supplicant\n"
#define NET_CONFIG "network={\n ssid=\"%s\"\n psk=\"%s\"\n}\n\n"
#define COLRED "\033[1;31;40m"
#define COLGRN "\033[1;32;40m"
#define COLEND "\033[0m"
void show_help(char** argv);
int main(int argc, char** argv)
{
//config options
char* ssid = NULL;
char* psk = NULL;
char* remark = NULL;
char* interface = NULL;
FILE* fp = NULL;
//getopt options
int c;
int option_index = 0;
int digit_optind = 0;
int this_option_optind;
int delflg = 0;
static struct option long_options[] = {
{"ssid", required_argument, 0, 's'},
{"psk", required_argument, 0, 'p'},
{"show", no_argument, 0, 'v'},
{"remark", required_argument, 0, 'r'},
{"help", no_argument, 0, 'h'},
{"if", required_argument, 0, 'i'},
{"delete", no_argument, 0, 'd'},
{0, 0, 0, 0 }
};
if (argc < 2) {
show_help(argv);
}
while (1) {
this_option_optind = optind ? optind : 1;
c = getopt_long(argc, argv, "i:s:p:r:hvd", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 's':
ssid = optarg;
break;
case 'p':
psk = optarg;
break;
case 'r':
remark = optarg;
printf("set remark info : unfinished\n");
goto END;
break;
case 'd':
delflg = 1;
printf("delete setting : unfinished\n");
goto END;
break;
case 'i':
interface = optarg;
printf("change interface : unfinished\n");
goto END;
break;
case 'h':
default:
show_help(argv);
}
}
if ((NULL == ssid && NULL != psk) || (NULL != ssid && NULL == psk) || \
(1 == delflg && (NULL == ssid|| NULL == psk))) {
show_help(argv);
}
fp = fopen(CONFIG_FILE, "r");
if (NULL == fp) {
fp = fopen(CONFIG_FILE, "w");
if (NULL == fp) {
perror("fopen failed");
goto END;
}
fprintf(fp, "%s\n", DEFAULT_IF);
} else {
fclose(fp);
fp = fopen(CONFIG_FILE, "a");
}
fprintf(fp, NET_CONFIG, ssid, psk);
fclose(fp);
END:
exit(EXIT_SUCCESS);
}
void show_help(char** argv)
{
printf(COLRED"Usage: %s [--delete] --ssid=SSID --psk=PSK [--remark=REMARK] [--if=NEWIF]"COLEND"\n", argv[0]);
printf("add or del wifi info int the file %s\n\n", CONFIG_FILE);
printf("Mandatory arguments to long options are mandatory for short options too.\n");
printf(COLGRN" -s, --ssid=SSID "COLEND"service set identifier\n");
printf(COLGRN" -p, --pak=PSK "COLEND"pre-shared key\n");
printf(COLGRN" -r, --remark=REMAKR "COLEND"comment for the setting\n");
printf(COLGRN" -h, --help "COLEND"show this help page and exit the program\n");
printf(COLGRN" -i, --if=INTERFACE "COLEND"change the default wifi interface\n");
printf(COLGRN" -d, --delete "COLEND"delete the specified setting\n");
printf(COLGRN" -v, --show "COLEND"show all setting in the config file\n");
printf("\nThanks for using this program!\n\n");
exit(EXIT_SUCCESS);
}