[英]replicate current path with color in C
我正在使用Linux Ubuntu,我想用着色復制終止的當前路徑。 從本質上講,我想我的程序打印\\u@\\h:\\w$
喜歡這個崗位與用戶終端的着色。 換句話說,將(user)@(host):(pwd)$
的路徑精確復制到着色。
我遇到的兩個問題:
1)我正在嘗試使用system("\\u@\\h:\\w$ ")
,但是無論如何我都無法轉義特殊字符。
2)我找不到用戶使用的顏色。
這里有幾個問題。
解析PS1
環境變量由外殼完成。 Shell(例如bash)正在將'\\ u'字符串轉換為'(user)'。 這不是系統調用。
系統調用執行一個文件名,因此通過執行system("\\u@\\h:\\w$ ")
您想要執行一個名為\\u@\\h:\\w$
。 我認為您的系統上沒有這樣的程序,這不是您的意圖。 您要打印當前記錄的用戶名,而不是執行名為“ \\ u”的程序。 您要執行一個名為whoami的程序,該程序將打印當前用戶的用戶名。
我不知道你想要什么顏色。 在unix shell中使用ANSI轉義碼進行着色。 您只需要打印一堆字符,終端就會為以下所有字符着色。
無論如何,用C程序打印此精確輸出要比這復雜得多。 以下程序將輸出(user)@(host):(pwd)$
。 部分(user)@
將為紅色,部分(host):
將為黃色,部分(pwd)$
將為品紅色。 我正在使用popen posix調用來執行一個過程並獲取它的輸出。
#define _GNU_SOURCE
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
void exec_and_grab_output(const char cmd[], char *outbuf, size_t outbuflen) {
size_t outbufpos = 0;
FILE *fp;
char tmpbuf[100];
/* Open the command for reading. */
fp = popen(cmd, "r");
assert(fp != NULL);
/* Read the output a line at a time - output it. */
while (fgets(tmpbuf, sizeof(tmpbuf)-1, fp) != NULL) {
assert(outbufpos <= outbuflen);
const size_t tmpbufpos = strlen(tmpbuf);
memcpy(&outbuf[outbufpos], tmpbuf, tmpbufpos);
outbufpos += tmpbufpos;
}
/* close */
pclose(fp);
}
int main()
{
char outbuf[2048];
exec_and_grab_output("whoami", outbuf, sizeof(outbuf));
printf(ANSI_COLOR_RED);
assert(strlen(outbuf) > 2);
outbuf[strlen(outbuf)-2] = '\0'; // remove newline from output
printf("%s@", outbuf); // this will be red
exec_and_grab_output("hostname", outbuf, sizeof(outbuf));
printf(ANSI_COLOR_YELLOW);
assert(strlen(outbuf) > 2);
outbuf[strlen(outbuf)-2] = '\0'; // remove newline from output
printf("%s:", outbuf); // this will be yellow
exec_and_grab_output("pwd", outbuf, sizeof(outbuf));
printf(ANSI_COLOR_MAGENTA);
assert(strlen(outbuf) > 2);
outbuf[strlen(outbuf)-2] = '\0'; // remove newline from output
printf("%s$", outbuf); // this will be in magenta
printf(ANSI_COLOR_RESET);
return 0;
}
如果要在shell中着色PS1變量的輸出(不是C語言,C是一種編程語言,shell是一個程序),則可以在bash終端中鍵入:
export PS1="\033[31m\u@\033[33m\h:\033[36m\w$\033[0m"
\\033[31m
部分與上面的C程序中的"\\x1b[31m"
部分1:1對應。 Bash將在終端上打印\\033[31m
字符(在打印PS1時),然后終端將隨后的所有字符着色為紅色。 Bash將
\\u\u003c/code>擴展為當前用戶的名稱。
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.