我正在尝试将getopt()用于需要“e”或“d”选项来选择加密或解密然后将一个密钥用于其中的程序。我的问题是我不知道如何使用getopt()来处理密钥。我已经阅读了很多man getopt()的东西以及其他许多文章。我目前得到一个浮点错误和核心转储,并收到警告信息:
cypher.c:在函数'main'中: cypher.c:14:3:警告:从不兼容的指针类型[默认启用]传递'getopt'的参数2 /usr/include/getopt.h:152:12:注意:预期'char * const *'但参数类型为'char * ' cypher.c:28:13:警告:赋值在没有强制转换的情况下从指针生成整数[默认启用]
以下是任何帮助的实际代码。
include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(int argc, char **argv[]){
int e,x;
int i=0;
int c=fgetc(stdin);
// int n=strlen(key);
int encrypt;
while((x = getopt (argc, argv, "ed")) != -1){
switch (x){
case 'e':
encrypt=1;
break;
case 'd':
encrypt=0;
break;
default:
fputs("you broke it\n",stderr);
exit(1);
}
}
char key[100];
key[100]= argv[optind++];
int n = strlen(key);
if(encrypt == 1){
while(c != EOF){
c= fgetc(stdin);
e=(c - 32 + key[i % n]) % 95 +32;
fputc( e, stdout);
i++;
}
}
else{
while( e != EOF){
c = fgetc(stdin);
c=(e - 32 -key[i % n] +3 * 95) % 95 +32;
fputc(c, stdout);
i++;
}
}
exit (0);
}
答案 0 :(得分:3)
通常,您希望将选项处理分为两个步骤:
所以基本上你可能想要设置一个全局变量(例如opt_mode = ENCRYPT
或opt_mode = DECRYPT
或类似的东西),并根据需要存储密钥。然后,在完成所有选项处理后,实际上基于opt_mode
变量进行加密或解密。
答案 1 :(得分:0)
Linux上的大多数新人甚至都不知道man
,Windows中没有man
。
另外,我的系统管理员可能没有安装包。如果您可以在计算机上安装软件包,请安装软件包:
sudo apt get install manpages-dev # on debian based systems
这是一个有用的资源,您可以找到所有可能的手册页列表:
dpkg -L manpages-dev
以下是您要找的地方:
$ dpkg -L manpages-dev| grep getop
/usr/share/man/man3/getopt.3.gz
/usr/share/man/man3/getopt_long_only.3.gz
/usr/share/man/man3/getopt_long.3.gz
这是一个很好的例子,明确的文字,添加到手册页(往往简洁)......
http://linuxprograms.wordpress.com/2012/06/22/c-getopt-example/
答案 2 :(得分:0)
getopt(3)有一个非常好的例子:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit(EXIT_SUCCESS);
}