在简单 shell 中用 $HOME 替换波形符
我正在用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在寻找的是
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.