在 C 中对命令行输入进行标记
尝试获取一行文本并将其标记为 execvp()
的文件名和参数。这是我的代码,getArguments()
是损坏的函数。目前,尝试打印 arguments[0]
会导致总线错误。
char* getFilename(char* input) {
return strtok(input, " &");
}
char** getArguments(char* input) {
char** arguments;
int k = 0;
char* tokenized;
tokenized = strtok(input, " &");
tokenized = strtok(NULL, " &");
while (tokenized != NULL) {
arguments[k] = tokenized;
++k;
tokenized = strtok(NULL, " &");
}
return arguments;
}
我稍后在代码中按以下方式使用它:
char* filename = getFilename(line);
char** arguments = getArguments(line);
trying to take a line of text and tokenize it into a filename and arguments for execvp()
. Here's my code, getArguments()
is the broken function. Currently, trying to print arguments[0]
results in a bus error.
char* getFilename(char* input) {
return strtok(input, " &");
}
char** getArguments(char* input) {
char** arguments;
int k = 0;
char* tokenized;
tokenized = strtok(input, " &");
tokenized = strtok(NULL, " &");
while (tokenized != NULL) {
arguments[k] = tokenized;
++k;
tokenized = strtok(NULL, " &");
}
return arguments;
}
I am using it in the following manner later in my code:
char* filename = getFilename(line);
char** arguments = getArguments(line);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对 getFilename 的调用通过在第一个标记后面放置“\0”字符来修改字符串。然后您尝试在 getArguments 中从头开始重新启动。由于字符串现在提前终止,因此只会产生第一个标记。您可以通过摆脱 getFilename 并从 getArguments 获取它来解决此问题。
此外,您必须为
char **arguments;
数组中的每个指针分配空间。您可以使用 realloc 动态增长数组。然而,还有更有效的方法。The call to getFilename modifies the string by placing a '\0' character after the first token. Then you attempt to restart at the beginning in getArguments. That only yields the first token since the string is now prematurely terminated. You can fix this problem by getting rid of getFilename and getting it from getArguments.
Also, you must allocate space for each pointer in the
char **arguments;
array. You can use realloc to grow the array dynamically. However, there are more efficient approaches.您还没有为
char **arguments
分配任何内存 - 它只是一个悬空指针。You haven't allocated any memory for
char **arguments
- it's just a dangling pointer.char **arguments
是单个指针。考虑它指向哪里......提示:它应该指向可以容纳多个指针的有用位置。
char **arguments
is a single pointer. Consider where it points....Hint: it should point somewhere useful where it can hold multiple pointers.