사용 함수-1(readline)

hyenam·2021년 11월 29일

minishell

목록 보기
2/6

readline

문자열을 입력받는 함수.
입력받은 문자열을 저장하고 그 메모리 주소를 반환한다.
빈 문자열일 경우는 NULL반환.
사용하면 꼭 free()해야한다.
컴파일 할때는 -lreadline 을 꼭 추가해야한다.

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
# include <stdlib.h>

int main(void)
{
	char *a;

	a = readline("input :");
	printf("%s", a);
	free(a);
}

rl_on_new_line

Tell the update routines that we have moved onto a new (empty) line, usually after ouputting a newline.
업데이트 루틴에 일반적으로 새 라인을 연결한 후 새(빈) 라인으로 이동했다고 알립니다.

일종의 알림형태의 함수이다.
readline디렉토리 내에서 update와 관련된 함수들에게 커서가 개행문자를 통해 다음 줄로 이동한 것을 알려주는 함수이다.

개행 문자 출력 이후 이용됨.

잘 수행되면 0을 반환, 오류가 있다면 -1반환

  • 프로토 타입
    int rl_on_new_line(void)
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
# include <stdlib.h>

int main(void)
{
	char *a;

	a = readline("input :");
	printf("%d\n" ,rl_on_new_line());
	printf("%s\n", a);
	printf("%d\n" ,rl_on_new_line());
	free(a);
}

일단 이렇게 썼을때 둘다 출력결과로 0이 나온다.
아직 이해를 잘 못해서 차후 추가 공부가 필요하다.

rl_replace_line

Replace the contents of rl_line_buffer with text. The point and mark are preserved, if possible. If clear_undo is non-zero, the undo list associated with the current line is cleared.


rl_line_buffer의 내용을 텍스트로 바꿉니다. 가능한 경우 포인트와 마크는 보존됩니다. clear_undo가 0이 아니면 현재 줄과 관련된 실행 취소 목록이 지워집니다.

프로토 타입
void rl_replace_line (const char *text, int clear_undo)

컴파일 할때

READLINE_LIB 	= -lreadline -L/usr/local/opt/readline/lib
READLINE_INC	= -I/usr/local/opt/readline/include

READLINE_LIB 	= -lreadline -L /Users/$(USER)/.brew/opt/readline/lib
READLINE_INC	= -I /Users/$(USER)/.brew/opt/readline/include

둘 중 하나를 옵션으로 넣어야컴파일이 됨

자료가 별로 없어서 추후 추가 예정

rl_redisplay

Change what's displayed on the screen to reflect the current contents of rl_line_buffer.


현재 rl_line_buffer의 내용을 반영하여 화면에 표시되는 내용을 변경합니다.

프로토 타입
void rl_redisplay (void)

자료가 별로 없어서 추후 추가 예정

add_history

받은 문자열을 history list 맨 끝에 위치 시켜주는 함수이다.
쉘에서는 자신이 입력한 명령어를 볼수있는 명령어가 있는데 그것을 구현하기 위해 사용되는 함수같다.

// 코드 수정하기

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<readline/readline.h>
#include<readline/history.h>

int main(void)
{
	char *a;
	int i;

	using_history(); //history list 초기화
	i = -1;
	while (++i < 5)
	{
		a = readline("input>");
		add_history(a); //history list에 문자열 추가
		free(a);
	}

	HIST_ENTRY **mylist = history_list (); // history list 가져오기
	for (int i = 0; mylist[i]; i++)
		printf("%d: %s\n", i + history_base, mylist[i]->line);
	free(mylist);
}

실행결과
input>a
input>b
input>c
input>d
input>e
1: a
2: b
3: c
4: d
5: e

HIST_ENTRY는 구조체이다

typedef struct _hist_entry {
  char *line; //문자열이 담기는 변수
  char *data;
} HIST_ENTRY;

학습에 참고한 사이트

profile
공부한 걸 정리하고 있습니다.

0개의 댓글