我正在用C编写一个简单的Unix shell。这是我到目前为止所拥有的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
char x[256], y[256], z[256];
while (1) {
getcwd(y, sizeof(y));
printf("%s$ ", y);
fgets(x, sizeof(x), stdin);
if (x[0] == 'c' && x[1] == 'd' && x[2] == ' ') {
sscanf(x, "cd %s", &z);
chdir(z);
}
else if (strcmp(x, "exit\n") == 0) break;
else system(x);
}
return 0;
}
我想做的是使波形符(〜)和$ HOME可以互换。我想我可以用一个简单的查找和替换功能来做到这一点。有谁知道这样的事情?
答案 0 :(得分:0)
我认为你要找的是strstr()
,它定位一个字符串中的子串,strchr()定位一个字符。当您找到起始索引时,您会将~
之前和之后的字符串部分复制到新字符串中。
An implementation of str_replace is included in this question