题
我正在做学校作业。编写一个简单的命令行解释器。功能之一是清屏。它的名字叫cmd_clr。为此,我尝试使用curses.h 库中的clear() 函数。问题是由于某种原因,clear() 返回 -1 值。这是代码:
#include <stdio.h> /* Standard IO functions */
#include <string.h> /* String library, might be useful */
#include <dirent.h> /* Directory entry API */
#include <curses.h> /* Useful for screen control */
#include <unistd.h> /* Process management API */
/* Global constants */
#define true 1
#define false 0
/* Global variables, structures */
char pwd[512];
char shell[512];
void cmd_dir(char []);
void cmd_cd(char []);
void cmd_clr(void);
int main (void)
{
char prompt[512] = {":#"};
char command[512];
char temp[512];
char* token;
while (true)
{
/* Print command prompot, including PWD */
printf("%s%s ", pwd, prompt);
/* Get command input */
gets(command);
/* Isolate the command token */
strcpy(temp, command);
token = strtok (temp, " ");
void cmd_dir(char directory[])
{
printf("shell command: dir\n");
token = strtok(NULL, " "); //to get the directory
execlp("/bin/ls","ls", "-l", token, NULL);
}
void cmd_cd(char directory[])
{
printf("shell command: cd\n");
token = strtok(NULL, " "); //to get the directory
chdir(token);
system("pwd");//to print the current directory
}
void cmd_clr(void)
{
printf("shell command: clr\n");
int tv = clear();
printf("%d", tv);
}
if (strcmp(token, "dir") == 0)
{
cmd_dir(command);
}
else if (strcmp(token, "cd") == 0)
{
cmd_cd(command);
}
else if (strcmp(token, "clr") == 0)
{
cmd_clr();
}
}
}
输出是:
mekhron@ubuntu:~/folder4$ gcc -o test test.c -lncurses
mekhron@ubuntu:~/folder4$ ./test
:# clr
shell command: clr
-1:# ^C
mekhron@ubuntu:~/folder4$
解决方案
诅咒 clear()
功能,像大多数一样 curses
函数,必须先调用才能使用 initscr()
.
从代码的其余部分来看,您可能不想使用 curses
或者 ncurses
反正。 curses
旨在管理您的整个屏幕。它与您正在执行的其他 I/O 不兼容。这 curses
clear()
功能不仅仅是清除屏幕;它清除了 curses
屏幕状态的内部表示。在您致电之前,您的实际屏幕不会被清除 refresh()
.
如果你只想立即清除屏幕,你应该找到另一种方法来做到这一点。这 clear
命令应该做到这一点;只要打电话 system("clear");
.
我还需要指出一件事:您正在使用 gets()
功能。不。 gets()
无法安全使用;由于它不允许您指定要读取的数组的大小,因此它无法防止长输入行溢出数组并破坏其他内存。这 fgets()
函数使用起来有点困难(特别是,它存储尾随 '\n'
在你的数组中),但它可以安全地使用。
假设您的编译器支持它,您可以删除以下定义 false
和 true
只需添加 #include <stdbool.h>
到程序的顶部。
不隶属于 StackOverflow