1
1
package object
2
2
3
+ import (
4
+ "os"
5
+ )
6
+
3
7
type File struct {
4
8
Filename string
5
- Content string // To read the file
9
+ Content string
6
10
}
7
11
8
12
func (f * File ) Type () ObjectType { return FILE_OBJ }
@@ -11,6 +15,10 @@ func (f *File) Method(method string, args []Object) Object {
11
15
switch method {
12
16
case "soma" :
13
17
return f .read (args )
18
+ case "andika" :
19
+ return f .write (args )
20
+ case "ongeza" :
21
+ return f .append (args )
14
22
}
15
23
return nil
16
24
}
@@ -21,3 +29,40 @@ func (f *File) read(args []Object) Object {
21
29
}
22
30
return & String {Value : f .Content }
23
31
}
32
+
33
+ func (f * File ) write (args []Object ) Object {
34
+ if len (args ) != 1 {
35
+ return newError ("Samahani, tunahitaji Hoja 1, wewe umeweka %d" , len (args ))
36
+ }
37
+ content , ok := args [0 ].(* String )
38
+ if ! ok {
39
+ return newError ("Samahani, hoja lazima iwe Tungo" )
40
+ }
41
+ err := os .WriteFile (f .Filename , []byte (content .Value ), 0644 )
42
+ if err != nil {
43
+ return newError ("Hitilafu katika kuandika faili: %s" , err .Error ())
44
+ }
45
+ f .Content = content .Value
46
+ return & Boolean {Value : true }
47
+ }
48
+
49
+ func (f * File ) append (args []Object ) Object {
50
+ if len (args ) != 1 {
51
+ return newError ("Samahani, tunahitaji Hoja 1, wewe umeweka %d" , len (args ))
52
+ }
53
+ content , ok := args [0 ].(* String )
54
+ if ! ok {
55
+ return newError ("Samahani, hoja lazima iwe Tungo" )
56
+ }
57
+ file , err := os .OpenFile (f .Filename , os .O_APPEND | os .O_WRONLY , 0644 )
58
+ if err != nil {
59
+ return newError ("Hitilafu katika kufungua faili: %s" , err .Error ())
60
+ }
61
+ defer file .Close ()
62
+ _ , err = file .WriteString (content .Value )
63
+ if err != nil {
64
+ return newError ("Hitilafu katika kuongeza kwa faili: %s" , err .Error ())
65
+ }
66
+ f .Content += content .Value
67
+ return & Boolean {Value : true }
68
+ }
0 commit comments