added code comments
[CleanReadLine.git] / Clean System Files / readLine.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include <readline/readline.h>
5 #include <readline/history.h>
6
7 #include "Clean.h"
8
9 static char *cs_answer = (char *)NULL;
10
11 char *cleanStringToCString(CleanString s){
12 unsigned long len = CleanStringLength(s);
13 char *cs = (char *)malloc(len+1);
14 if(cs == NULL){
15 printf("malloc failed...\n");
16 exit(1);
17 }
18 memcpy(cs, CleanStringCharacters(s), len);
19 cs[len] = '\0';
20 return cs;
21 }
22
23 int cleanReadHistory(CleanString path)
24 {
25 char *cs_path = cleanStringToCString(path);
26 int errno = read_history(cs_path);
27 free(cs_path);
28 return errno;
29 }
30
31 int cleanReadHistoryRange(CleanString path, int from, int to)
32 {
33 char *cs_path = cleanStringToCString(path);
34 int errno = read_history_range(cs_path, from, to);
35 free(cs_path);
36 return errno;
37 }
38
39 int cleanWriteHistory(CleanString path)
40 {
41 char *cs_path = cleanStringToCString(path);
42 int errno = write_history(cs_path);
43 free(cs_path);
44 return errno;
45 }
46
47 int cleanAppendHistory(int n, CleanString path)
48 {
49 char *cs_path = cleanStringToCString(path);
50 int errno = append_history(n, cs_path);
51 free(cs_path);
52 return errno;
53 }
54
55 int cleanHistoryTruncateFile(CleanString path, int nlines)
56 {
57 char *cs_path = cleanStringToCString(path);
58 int errno = history_truncate_file(cs_path, nlines);
59 free(cs_path);
60 return errno;
61 }
62
63 void cleanReadLine(CleanString prompt, int history, CleanString *result)
64 {
65 char *cs_prompt = cleanStringToCString(prompt);
66
67 //Get the answer and add to history if not empty
68 if(cs_answer){
69 free(cs_answer);
70 cs_answer = (char *)NULL;
71 }
72 cs_answer = readline(cs_prompt);
73 free(cs_prompt);
74 if(cs_answer && *cs_answer && history){
75 add_history(cs_answer);
76 }
77
78 if(!cs_answer){ //In case of an EOF
79 CleanStringVariable(answer, 1);
80 *result = (CleanString) answer;
81 memcpy(CleanStringCharacters(answer), "", 1);
82 CleanStringLength(answer) = 1;
83 } else { //In case of a proper response
84 CleanStringVariable(answer, strlen(cs_answer));
85 *result = (CleanString) answer;
86 memcpy(CleanStringCharacters(answer), cs_answer, strlen(cs_answer));
87 CleanStringLength(answer) = strlen(cs_answer);
88 }
89 }