是否有更好的方式接受输入, 例如: ls =列出当前目录中的所有文件... cat Q1.c将显示等
对我来说,似乎我现在很难对其进行编码
int main(int argc, char *argv[])
{
int i;
char *dest = NULL;
if(argc==1) {
printf( "No arguments were passed.\n" );
}
else {
printf("Arguments:\n");
for(i=1;i<argc;++i) {
printf("%d. %s\n", i, argv[i]);
dest = malloc(strlen(argv[i])+1);
if(i<2) {
sprintf(dest, "%s",argv[i]);
}
else {
sprintf(dest, "%s %s", argv[i-1], argv[i]);
}
}
mysystem(dest);
}
return 0;
}
答案 0 :(得分:1)
正如Bruce在评论中所说,我猜你正在为这个选项寻找一个快速解析器。 getopt()和getopt_long()会让您轻松解析您的论点,但请注意这些是POSIX的成员!
getopt():。/ example -a udp://127.0.0.1:8000
getopt_long():。/ example --address = udp://127.0.0.1:8000
答案 1 :(得分:1)
您没有为mysystem
建立缓冲区。这是工作代码[请原谅无偿风格的清理]:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int
main(int argc, char *argv[])
{
int i;
char *dest = NULL;
char *dp;
char *av;
int totlen;
int len;
if (argc == 1) {
printf("No arguments were passed.\n");
}
else {
// get total amount of space we'll need
totlen = 0;
for (i = 1; i < argc; ++i) {
av = argv[i];
len = strlen(av);
totlen += len + 1;
}
dest = malloc(totlen + 1);
dp = dest;
*dp = 0;
printf("Arguments:\n");
for (i = 1; i < argc; ++i) {
av = argv[i];
printf("%d. %s\n", i, av);
if (i > 1)
*dp++ = ' ';
strcpy(dp,av);
dp += strlen(av);
}
system(dest);
}
return 0;
}