问题
I just moved to Linux for just a month. I've used Borland Turbo C for C programming but some of these functions do not work in GNU/Linux, so looking for help.
These are some of the functions I would like to replace:
- gotoxy
- cprintf
- clrscr
- initgraph/graphics.h
I would appreciate some code examples showing how to use any replacements.
回答1:
In linux, you can use the ncurses library to use the terminal as a text buffer: move the cursor around, and write text. It can also draw windows and other hi-level widgets.
For gotoxy
see move
and wmove
from ncurses (link).
For cprintf
see printw
.
You can clear the screen simply with clear()
.
In ncurses you also need to refresh the screen with refresh()
after printw
and clear()
.
Example program, which uses all the mentioned functions in ncurses:
#include <curses.h>
int main(int argc, char *argv[])
{
initscr();
clear();
move(15, 20);
printw("Test program: %s", argv[0]);
refresh();
getch();
endwin();
return 0;
}
Compile in gcc with: gcc program.c -lcurses
As for graphics, you have to choose a particular library. If you need a similar experience as the low-level graphics.h, you are probably looking for directfb or svgalib. If you want to render graphics in a window, SDL will be helpful.
回答2:
The functions you refer to are part of Borland's proprietary library for console applications. You want to read about ncurses.
回答3:
About graphics.h
Regarding using graphics.h in Linux is an easy task. I had the same problem a week ago. Well you can goggle with search term "graphics.h in Linux", and you will get many links and here is one.
http://www.rajivnair.in/2007/07/graphicsh-in-gnulinux.html.
About Clear Screen
For that, you have many options. And the one is, using system("clear") but it needs stdlib.h and it is slower in performance. Here two links for you...
How do I clear the console in BOTH Windows and Linux using C++
cprogramming.com
About gotoxy As mentioned in Michał Trybus's Answer.
About cprintf
I Referred many links, but not getting the simple answers. Me too waiting for the answers for this.
But,In my experience whenever I want the output to be in some colored format , I will use graphics.h, though it is not required.That's why I doesn't had this question in my mind ever before.
You may find this link useful...
codeguru.com
About getch I think you may already know about this. Instead of getch() in conio.h(not in ansi standard), you can use getchar() in stdio.h.
回答4:
Just, I was answering the same questions in another thread:
void gotoxy(int x, int y) {
printf("%c[%d;%df",0x1B, y, x);
}
void clrscr(void) {
fprintf(stdout, "\033[2J\033[0;0f");
fflush(stdout);
}
void textcolor(int attr, int fg, int bg) {
printf("%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
}
Easy way to do it!
来源:https://stackoverflow.com/questions/7079943/gnu-linux-replacements-for-turbo-c-functions-clrscr-and-cprintf