[英]C strtok() and strcmp() issues
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int args, char* argv[])
{
const int CBUFF = 1024;
char input[CBUFF];
char wkdir[CBUFF];
char* command;
printf("Welcome to MyShell...\n");
while(1)
{
getcwd(wkdir, CBUFF);
printf("%s ? ", wkdir);
fgets(input, CBUFF, stdin);
command = strtok(input, " ");
if(strcmp(command, "cd") == 0)
{
char* path;
path = strtok(NULL, " ");
if(chdir(path) != 0)
{
printf("ERROR: COULD NOT CHANGE DIRECTORY TO SPECIFIED PATH");
}
}
if(strcmp(command, "exit") == 0) break;
}
return 0;
}
I am running into an issue creating a very simple command shell in C
.我在 C 中创建一个非常简单的命令C
时遇到了问题。 The input is only being read the way I want it too when I add a space after my directive.当我在指令后添加一个空格时,输入也只会按照我想要的方式被读取。 I know that it has something to do with my improper use of the strtok()
function but am not able to figure out what I am doing wrong.我知道这与我对strtok()
function 的不当使用有关,但我无法弄清楚我做错了什么。 I have read the documentation of <string.h>
and am turning up blank.我已经阅读了<string.h>
的文档,结果一片空白。
Behavior I want: Directive "exit" to exit from program.我想要的行为:指令“exit”退出程序。 Current behavior: Must add space after directive to get it to parse correctly ie.当前行为:必须在指令后添加空格才能正确解析,即。 "exit " or "cd " is entered.输入“exit”或“cd”。
You left the trailing newline in the buffer.您在缓冲区中留下了尾随的换行符。 Get rid of it.摆脱它。
char *got = fgets(input, CBUFF, stdin);
if (!got) return ; /* EOF -- treat like exit */
size_t gotlen = strlen(got);
if (got[gotlen] == '\n') got[gotlen] = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.