]> pd.if.org Git - pd_readline/blob - history.c
More work.
[pd_readline] / history.c
1
2
3 /*  history.c                                          */ 
4 /*  Command history.                                   */ 
5 /*  This code is released to the public domain.        */ 
6 /*  "Share and enjoy...."  ;)                          */  
7 /*  See the UNLICENSE file for details.                */ 
8
9 #include <string.h>   
10 #include <stdio.h> 
11 #include <stdlib.h> 
12 #include <malloc.h>
13 #include "pd_readline.h"  
14
15
16 /*  Helper function, to let us see if a file */ 
17 /*  exists in the current directory.  */ 
18 int fexists(char *fname)
19 {  
20    FILE *fptr;  
21    fptr = fopen(fname, "r") ;     
22    if ( !fptr )  return -1 ;  /* File does not exist in dir. */                  
23    fclose(fptr);  
24    return 0;    /* File DOES exist in dir.  */   
25
26
27
28 /* Helper function to chop newlines off the lines read in. */ 
29 /* Without this being done, an extra newline is inserted */ 
30 /* (which is usually not what is wanted). */ 
31 char *chop(char *s)
32 {
33   s[strcspn(s,"\n")] = '\0'; 
34   return s; 
35 }
36
37
38 /* An array to store the command-history file in. */ 
39 /* Only 20 lines are read. */ 
40 char hist[20][80];  
41
42
43
44 /* Read the file into the array of strings.                */ 
45 buf readhistory(char *fname) 
46
47         
48    /*  Create a history buffer.  */ 
49    buf h;       
50         
51    int retval = fexists(fname); 
52         
53    int i; 
54    if (retval == 0) { 
55           /* File exists, so open it. */  
56           /* We open it in read-write mode so we can */ 
57           /* append new commands to it. */ 
58           FILE *fptr;  
59           fptr = fopen(fname, "rw"); 
60                 
61       char line[80] ; 
62                                            
63           for(i=0; i<20; i++)  
64           { 
65                 fgets(line, 80, fptr);                   
66                 chop(line) ;   
67                 memcpy(hist[i], line, 80) ;   
68                 puts(hist[i]); 
69           }
70           
71    }  /* retval == 0  */           
72         
73         else puts("Error! File does not exist. \n");  
74         
75         /* Read the most recent command into histbuf */ 
76         /* and set the index to 19.                  */
77         /*  
78             h.index = 19; 
79         h.array = hist[h.index] ;  
80     */
81         
82         return h;
83         
84 }       
85
86                                            
87
88  
89
90
91