在简单 shell 中用 $HOME 替换波形符

发布于 2024-09-24 03:51:13 字数 649 浏览 1 评论 0原文

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

I am writing a simple Unix shell in C. Here's what I have so far.

#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;
}

What I would like to do is make the tilde character (~) and $HOME interchangeable. I figured I could do this with a simple find-and-replace function. Does anyone know of such a thing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

源来凯始玺欢你 2024-10-01 03:51:13

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

包含 str_replace 的实现在这个问题中

I think what you're looking for is strstr(), which locates a substring in a string, and strchr() which locates a single character. When you've found the start index, then you would copy the parts of the string before and after the ~ into a new string.

An implementation of str_replace is included in this question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文