質問
私は学校の割り当てをしています。単純なコマンドラインインタプリタを書き込む。機能の1つは画面をクリアすることです。そのinは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 curses
関数は、最初に呼び出すことなく使用できません。 >。
あなたのコードの残りの部分による判断は、おそらくinitscr()
またはcurses
を使用したくないでしょう。 ncurses
は画面全体を管理するように設計されています。他のI / Oとは互換性がありません。 curses
curses
関数は、画面をクリアしていません。画面の状態のclear()
の内部表現を消去します。 curses
を呼び出すまで、実際の画面はクリアされません。
すぐに画面をクリアしたい場合は、別の方法を見つける必要があります。 refresh()
コマンドはそれをするべきです。 clear
を呼び出します。
もう1つのことを指摘する必要があること:あなたはsystem("clear");
関数を使用しています。しないでください。 gets()
は安全に使用できません。読んでいる配列のサイズを指定できないので、長い入力ラインがアレイを溢れ、他のメモリを隠すのを防ぐことはできません。 gets()
関数は、使用するのはもう少し難しいです(特に、アレイ内の末尾のfgets()
を格納します)が安全に使用できます。
およびコンパイラがそれをサポートすると仮定すると、'\n'
とfalse
の定義をドロップして、Programの上部にtrue
を追加するだけです。