LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 786|回复: 5

怎么在控制台输出彩色阿?

[复制链接]
发表于 2005-8-23 01:35:17 | 显示全部楼层 |阅读模式
用的编程语言是C
在bash下面,终端是VT100,支持彩色
现在想在屏幕上输出彩色,比如红色,表示警示作用
比如下面的语句
printf("\033[01;031m Error!!!!\033[0m\n");
输出bright red的Error
但是我需要重定向输出到文件的时候,比如#./a.out >> b.log
b.log 文件的内容出现相应的
^[[01;031m Error!!!!^[[0m\n

但是我不想要这些ascii烟色控制符,怎么办呢?
发表于 2005-8-23 09:26:17 | 显示全部楼层
./a.out >> b.log
你cat b.log就没有问题了
也可以判断输出是不是终端
回复 支持 反对

使用道具 举报

发表于 2005-8-23 09:29:51 | 显示全部楼层
在C中编制基于文本界面的程序要适当的学习一下CURSES
//--codes from beginning linux programming 3 rd

  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <curses.h>
  5. int main()
  6. {
  7. int i;
  8. initscr();
  9. if (!has_colors()) {
  10. endwin();
  11. fprintf(stderr, “Error - no color support on this terminal\n”);
  12. exit(1);
  13. }
  14. if (start_color() != OK) {
  15. endwin();
  16. fprintf(stderr, “Error - could not initialize colors\n”);
  17. exit(2);
  18. }
  19. endwin();
  20. exit(EXIT_SUCCESS);
  21. }
  22. clear();
  23. mvprintw(5, 5, “There are %d COLORS, and %d COLOR_PAIRS available”,
  24. COLORS, COLOR_PAIRS);
  25. refresh();
  26. init_pair(1, COLOR_RED, COLOR_BLACK);
  27. init_pair(2, COLOR_RED, COLOR_GREEN);
  28. init_pair(3, COLOR_GREEN, COLOR_RED);
  29. init_pair(4, COLOR_YELLOW, COLOR_BLUE);
  30. init_pair(5, COLOR_BLACK, COLOR_WHITE);
  31. init_pair(6, COLOR_MAGENTA, COLOR_BLUE);
  32. init_pair(7, COLOR_CYAN, COLOR_WHITE);
  33. for (i = 1; i <= 7; i++) {
  34. attroff(A_BOLD);
  35. attrset(COLOR_PAIR(i));
  36. mvprintw(5 + i, 5, “Color pair %d”, i);
  37. attrset(COLOR_PAIR(i) | A_BOLD);
  38. mvprintw(5 + i, 25, “Bold color pair %d”, i);
  39. refresh();
  40. sleep(1);
  41. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2005-8-23 09:39:31 | 显示全部楼层
Post by minus273
./a.out >> b.log
你cat b.log就没有问题了
也可以判断输出是不是终端

15 岁, 汗~~~~~~~~
我 15 岁的时候尚不知计算机为何物
回复 支持 反对

使用道具 举报

发表于 2005-8-23 10:45:06 | 显示全部楼层
minus273 确实是不可多得的好少年
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-8-24 06:11:39 | 显示全部楼层
Post by minus273
./a.out >> b.log
你cat b.log就没有问题了
也可以判断输出是不是终端

太赞了
用cat b.log还是有同样的问题,还是输出颜色代码
用判断终端方法解决,btw: 我不会curses编程 //shy

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main(void)
  4. {
  5.        if(isatty(STDOUT_FILENO)){
  6.                printf("\E[1;32mhi\E[0m");
  7.                fputs("\E[1;32mhi\E[0m\n",stdout);
  8.        } else {
  9.                printf("hi");
  10.                fputs("hi",stdout);
  11.        }
  12.        return 1;
  13. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表