【发布时间】:2019-02-19 08:54:20
【问题描述】:
我的任务是编写一个可以在 bash shell 中使用的程序,该程序模仿某些默认的 Unix 命令,我们应该从头开始构建它们。这些命令之一是 PS1 命令,它应该将 $ 提示符更改为给出命令的任何参数。我已经在下面的代码中实现了这一点,它几乎可以完美地工作。
在使用 PS1 命令之前,提示符正常工作,它打印 $ 并且不缩进,而是让用户继续在同一行上键入。但是,使用该命令后,每当出现提示时,程序都会打印提示,然后换行。我需要它来打印 PS1 char* 而无需换行。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
int exit = 0;
char* PS1 = "$";
while(exit == 0){
char* token;
char* string;
char input[500];
printf("%s", PS1);
fgets (input, 500, stdin);
token = strtok(input, " ");
if(strncmp(token, "exit", 4) == 0){
exit = 1;
break;
}
else if(strncmp(token, "echo", 4) == 0){
token = strtok (NULL, " ");
while (token != NULL){
printf ("%s", token);
printf("%s", " ");
token = strtok (NULL, " ");
}
}
else if(strcmp(token, "PS1") == 0){
token = strtok (NULL, " ");
char temp[300];
strcpy(temp, &input[4]);
PS1 = temp; }
}
}
【问题讨论】:
-
fgets读取的字符通常在末尾包含换行符。你可能想摆脱它。 -
fgets在末尾保留换行符,以便打印。分配给分配后立即超出范围的临时数组是这里更大的问题。 -
谢谢,n.m.,我可以通过
temp[strlen(temp) - 1] = '\0';解决它
标签: c unix command-line strcpy