【发布时间】:2010-09-16 15:19:44
【问题描述】:
我正在为我的操作系统类编写一个 linux shell。我已经淘汰了大部分,但我坚持简单的字符串比较。我有我能想到的一切。 strcmp 应该接受 \0 终止的字符串并返回 0 表示相等,但这似乎不起作用,甚至单步执行数组并检查每个字符也不起作用。我目前在 strcmp 中有 cmd[0] 我知道这是不对的,它需要以空值终止,但我尝试使用 strcpy 和 strcat \0 到另一个字符串。如果有人能指出我的错误,将不胜感激。
//Matthew Spiers
//CSC306
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
void ckCmd(char dir[]);
int main(){
pid_t pid;
char cdstr[4] = "cd";
char str[50];
char *cmd[3];
char *pstr;
char temp[50];
char dir[50] = "/bin/";
while(1){
pid = fork();
if(pid < 0){
fprintf(stdout, "Fork Failed");
}
else if(pid == 0){
fprintf(stdout, "\e[36m306.SH>\e[0m");
fgets(str, 50, stdin);
for(int i =0; i<50; i++){
if(str[i] == '\n'){
str[i] = '\0';
}
}
strcpy(temp, str); // Make a copy of original string
cmd[0] = strtok(str, " ");
for(int i =1; i<3; i++){
cmd[i] = strtok(NULL, " ");
}
strcat(dir, cmd[0]);
cout << cmd[0];
pstr = strtok(temp, " "); //pull out only first token
//Change Directory
if(!strcmp(pstr, "cd")){ //if first token is cd
//either branch to a routine just change directory
//ie branch and change directory
}
//ckCmd(temp);
execlp(dir, cmd[0], cmd[1], cmd[2], NULL);
_exit(0);
}
else{
wait(NULL);
}
}
}
void ckCmd(char str[]){
char *p;
p = strtok(str, " ");
if(p[0] == 'c'){
chdir("new");
}
}
enter code here
【问题讨论】:
-
即使你说的函数是纯C的,包含也表明你使用的是C++,所以我把标签去掉了,如果你认为合适的话,重新标记。一旦你打算使用 C++,我建议使用
std::string并避免完全使用strtok和strcmp,除非这是练习要求的一部分。 -
Edit 忽略了一行,没关系。
-
充满了错误(
iostream、using、namespace、cout) -
@Nikko:我不认为问题出在 C 上,有一些 C++ 独有的东西:
#include <iostream>、using namespace std;、cout -
@David :只是标准输出,可以用 C 等效项替换。