用简单shell中的$HOME替换tilde

用简单shell中的$HOME替换tilde,shell,unix,environment-variables,tilde,Shell,Unix,Environment Variables,Tilde,我正在用C编写一个简单的unixshell #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);

我正在用C编写一个简单的unixshell

#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可互换。我想我可以用一个简单的查找和替换函数来完成。有人知道这样的事情吗?

我想你要找的是strstrstr,它定位字符串中的子字符串,strchr定位单个字符。找到开始索引后,将~之前和之后的字符串部分复制到新字符串中


.

要像一个真正的shell,您不希望它们可以互换-这样您就根本无法输入tilde。您可以先用$HOME值替换单词开头的不带引号的波浪线。