我试图模仿GNU find命令。我将所有命令选项都设为linkedlist
。我正在尝试处理argv中的所有选项并将它们存储在链表中。每个node
一个选项,但似乎没有更新。我认为当函数返回时,它仍然指向最后一个node
int main(int argc, char *argv[]) {
char *path_list[argc];
s_option *p = process_parms(argc, path_list, argv);
char **pp = path_list;
printf("%s \n", path_list[0]); // prints Documents/
printf("help is %d\n",p->help); // it doesn't work. is 0 should be 1
return 0;
}
typedef struct _allopts {
int help;
int print;
char f_type;
int ls;
char *user;
unsigned long user_id;
char *name;
struct _allopts *next;
} s_option;
s_option *process_parms(const int len, char *spath[], char **pms) {
int index = 0;
s_option *op = malloc(sizeof(struct _allopts));
for (int i = 1; (i < len); ++i, op = op->next) {
op->next = malloc(sizeof(struct _allopts));
if (op->next == NULL) {
fprintf(stderr, "myfind: calloc(): %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (strcmp(pms[i], "-name") == 0) {
size_t l = strlen(pms[i]);
op->name = malloc(sizeof(char) * l + 1);
strcpy(op->name, pms[i]);
op->name[l + 1] = '\0';
continue;
} else if (strcmp(pms[i], "-help") == 0) {
op->help = 1;
continue;
} else if (strcmp(pms[i], "-print") == 0) {
op->help = 1;
continue;
} else if (strcmp(pms[i], "-ls") == 0) {
op->ls = 1;
continue;
} else if (strcmp(pms[i], "-type") == 0) {
char f = *(pms[++i]);
if (f == 'f' || f == 'b' || f == 'c' ||
f == 'd' || f == 's' || f == 'p' || f == 'l') {
op->f_type = f;
continue;
} else {
printf("myfind: Unknown argument to %s: %c\n", pms[i-1], *pms[i]);
break;
}
} else
if (strcmp(pms[i], "-user") == 0) {
struct passwd *pd;
if (pms[++i]) {
op->user = strcpy(malloc(sizeof(strlen(pms[i]))), pms[i]);
if ((pd = getpwnam(pms[i]))) {
op->user_id = pd->pw_uid;
continue;
} else if (isdigit(pms[i][0])) {
sscanf(op->user, "%lu", &op->user_id);
continue;
} else {
printf("myfind: `%s` is not a the name of a known user \n", pms[i]);
break;
}
} else {
printf("myfind: missing argument to `%s`\n", pms[i]);
break;
}
}
/*Getting the path here.
* */
if (*(*(pms + 1)) != '-') {
size_t l = strlen(pms[i] + 1);
spath[index] = strcpy(malloc(sizeof(char) * l), pms[i]);
(spath+index)[l + 1] = '\0';
index++;
} else {
printf("myfind: Unknown predicate `%s`\n", pms[i]);
//docs/ doc1/ doc2/ -ls -type m -user james
break;
}
}
spath[index] = NULL;
return op;
}
我在这里错过了一些东西。我尝试使用带有printf的调试器,它非常好地更新了元素,但在主要内容它一直显示0以寻求帮助。 谢谢你的帮助。
答案 0 :(得分:1)
该函数返回最后一个节点,指针op:
指向该节点return op;
因为指针op在这里递增:
for (int i = 1; (i < len); ++i, op = op->next) {
^^^^^^^^^^^^^
复制指向第一个节点的指针并改为返回:
s_option *op = malloc(sizeof(struct _allopts));
s_option *first = op;
//...
return first;