【问题标题】:Replacing tilde with $HOME in simple shell在简单的 shell 中用 $HOME 替换波浪号
【发布时间】:2011-04-14 02:57:32
【问题描述】:

我正在用 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 可以互换。我想我可以用一个简单的查找和替换功能来做到这一点。有谁知道这样的事情吗?

【问题讨论】:

  • 要模拟一个真实的外壳,您不希望它们可以互换——那么您将根本无法输入波浪号。您可以先将单词开头的 unquoted 波浪号替换为 $HOME 的值。

标签: shell unix environment-variables tilde


【解决方案1】:

我认为您要查找的是strstr(),它定位字符串中的子字符串,而 strchr() 定位单个字符。找到起始索引后,您可以将~ 之前和之后的字符串部分复制到一个新字符串中。

An implementation of str_replace is included in this question.

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 2011-08-21
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2019-04-09
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多