]> pd.if.org Git - pd_readline/blob - readfile.c
Getting close to a basic working readline now.
[pd_readline] / readfile.c
1
2
3
4 /* readfile.c  */ 
5
6 /* Check that a file exists. */ 
7 /* If it does, read it into an array and print it out. */ 
8
9
10 #include <string.h>   
11 #include <stdio.h> 
12
13
14
15 /*  Helper function, to let us see if a file */ 
16 /*  exists in the current directory.  */ 
17 int fexists(char *fname)
18 {  
19    FILE *fptr;  
20    fptr = fopen(fname, "r") ;     
21    if ( !fptr )  return -1 ;  /* File does not exist in dir. */                  
22    fclose(fptr);  
23    return 0;    /* File DOES exist in dir.  */   
24
25
26
27 /* Helper function to chop newlines off the lines read in. */ 
28 /* Without this being done, an extra newline is inserted */ 
29 /* (which is usually not what is wanted). */ 
30 void chop(char *s)
31 {
32   s[strcspn(s,"\n")] = '\0';
33 }
34
35
36 /* An array to store the file in. */ 
37 /* Only 20 lines are read. */ 
38 char myarray[20][80];  
39
40
41 /* Read the file into the array of strings.  */ 
42 void readfile(char *fname) 
43
44    int retval = fexists(fname); 
45         
46    int i; 
47    if (retval == 0) { 
48           /* File exists, so open it. */  
49           /* We open it in read-write mode so we can */ 
50           /* append new commands to it. */ 
51           FILE *fptr;  
52           fptr = fopen(fname, "rw"); 
53                            
54           for(i=0; i<20; i++)  
55           {  
56                 chop(fgets(myarray[i], 80, fptr) );  
57           }
58           
59    }  /* retval == 0  */           
60         
61         else puts("Error! File does not exist. \n");  
62         
63 }       
64
65
66 void printfile(void) 
67
68   int j; 
69         
70   for(j=0; j<10; j++) 
71      { 
72         puts(myarray[j]);       
73      }    
74                 
75 }       
76
77
78
79 int main(void) 
80
81
82 readfile("test.txt"); 
83
84 printfile(); 
85
86
87 return 0; 
88
89 }  
90
91
92
93
94
95
96  
97
98