문제

나는 학교 과제를 하고 있어요.간단한 명령줄 해석기를 작성합니다.기능 중 하나는 화면을 지우는 것입니다.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> 프로그램 상단으로 이동하세요.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top