reading file
[sped.git] / sped.asm
1
2 global main
3 extern printf
4
5 ; macros
6 %macro write_str 2
7     mov eax, 4
8     mov ebx, 1
9     mov ecx, %1
10     mov edx, %2
11     int 0x80
12 %endmacro
13
14 section .data
15     banner_str db `SPED - the stupidly pointless editor\n`, 0x00
16     readfile_str db `reading file %s\n`, 0x00
17     nofile_str db `no file provided\n`, 0x00
18     argcount_str db `there are %d args\n`, 0x00
19     wrongfile_str db `unable to open file, error code: %i\n`, 0x00
20
21 ; section .bss
22
23 section .text
24 main:
25     push ebp
26     mov ebp, esp
27
28     ; read command line args
29     mov ecx, [ebp+8]
30     cmp ecx, 1
31     jg .main_existing
32     
33     ; display error msg if no file
34     push nofile_str
35     call printf
36     mov eax, 1
37     jmp .main_exit
38
39 .main_existing:
40     mov ebx, DWORD [ebp+12]
41     add ebx, 4
42     push DWORD [ebx]
43     ; push readfile_str
44     ; call printf
45
46     call readFile
47
48     mov eax, 0
49     jmp .main_exit
50
51 .main_exit:
52     mov esp, ebp
53     pop ebp
54     ret
55
56 ; reads file line by line
57 ; args: filename
58 ; return:
59 ;    eax - pointer to mem
60 ;    ecx - lines read
61 readFile:
62     %define _FILE_NAME 8
63     %define FILE_HANDLE 4
64
65     push ebp
66     mov ebp, esp
67     
68     ; allocate vars
69     sub esp, 4
70     mov DWORD [ebp-FILE_HANDLE], 0x00
71     
72     ; open existing file
73     mov eax, 5
74     mov ebx, [ebp+_FILE_NAME]
75     mov ecx, 0
76     mov edx, 0700
77     int 0x80
78     mov [ebp-FILE_HANDLE], eax
79
80     ; check if file was open successfully
81     cmp eax, 0
82     jge .readFile_noerror
83     push eax
84     push wrongfile_str
85     call printf
86     jmp .readFile_exit
87
88 .readFile_noerror:
89
90     jmp .readFile_exit
91
92 .readFile_exit:
93
94     ; close file
95     mov eax, 6
96     mov ebx, [ebp-FILE_HANDLE]
97     int 0x80
98
99     %undef _FILE_NAME
100     %undef FILE_HANDLE
101
102     mov esp, ebp
103     pop ebp
104     ret
105
106
107 ; reads a line until newline character is reached
108 ; args: file_handle
109 ; return: location to buffer
110 readLine:
111     
112     %define _FILE_HANDLE 8
113
114     push ebp
115     mov ebp, esp
116
117 .readLine_loop:
118
119     ; read a single character
120     mov eax, 3
121     mov ebx, [ebp+_FILE_HANDLE]
122     ; mov ecx, 
123     mov edx, 1
124     int 0x80
125
126     jmp .readLine_loop
127
128     mov esp, ebp
129     pop ebp
130     ret
131