【发布时间】:2015-04-02 18:53:35
【问题描述】:
所以基本上我正在编写一个程序,它重复地从标准输入中读取输入行,并将它们拆分为一个 char **array。对于每一行,将第一个元素视为要执行的程序的完整路径。执行程序,将行中的其余项目作为参数传递。如果该行为空,则什么也不做,然后转到下一行。重复直到第一个元素是字符串“exit”。
我的问题是:
- 当我输入“exit”时,strcmp(l[0], "exit") 返回 10 而不是 0。为什么?
- 程序已编译但仅适用于奇数个参数。 例如,如果我输入“/bin/echo This is good”,它会打印“This is good” 但是如果我输入“/bin/echo This is very good”,它会打印“error”。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 10000
int space;
char** createArray(char *line) {
int len_line = strlen(line);
char **wordArray = NULL;
if(len_line > 1){
char *token = strtok(line, " ");
space = 0;
while (token) {
wordArray = realloc(wordArray, sizeof(char*)*++space);
wordArray[space-1] = token;
token = strtok(NULL, " ");
}
}
return wordArray;
}
int main(int argc, const char* argv[]) {
char line[BUFSIZE];
while (1) {
printf("%s\n", ">");
fgets(line, BUFSIZE, stdin);
char** l = createArray(line);
if (l) {
/*why instaed of zero, when l[0]
/*equals quit, strcmp() returns 10?*/
printf("%d\n", strcmp(l[0], "exit"));
if(strcmp(l[0], "exit")==10) {
exit(0);
}
else if(fork() == 0) {
execv(l[0], l);
printf("%s\n", "Error!");
}
}
}
return 1;
}
【问题讨论】:
-
if(strcmp(l[0], "exit")==10)...或者你的意思是if(strcmp(l[0], "exit") == 0)? -
期望
strcmp()准确返回 10 是相当奇怪的。它返回零、正数(可能是 10)或负数。 -
你真的应该编译所有警告和调试信息(例如
gcc -Wall -Wextra -g)然后使用调试器(gdb)
标签: c