开发者

Replacing tilde with $HOME in simple shell

开发者 https://www.devze.com 2023-01-17 03:52 出处:网络
I am writing a simple Unix shell in C. Here\'s what I have so far. #include <stdio.h> #include <stdlib.h>

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] =开发者_JAVA技巧= '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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消