Author Topic: populating an array from a file  (Read 6587 times)

Offline cerberus

  • Jr. Member
  • *
  • Posts: 2
populating an array from a file
« on: October 25, 2012, 05:57:57 PM »
Hello, I am trying to read integers from a file using C functions. The first integer in the file is the count of integers in the file. The remaining integers are then summed up. I am having some trouble with populating the array of integers. Any comments or guidance would be much appreciated. Thank You. Here is what I have so far.

Code: [Select]
extern printf
extern fopen
extern fscanf
extern fclose
global main

SECTION .data
usage_str: db "proj2 filename", 10, 0
scan_fmt: db "%d", 0
file_mode: db "r", 10, 0
error_str: db "Cannot open file!", 10, 0

SECTION .bss
file_handle resd 1
buflen equ  256
buffer resd buflen
array resd arraylen
arraylen equ 256
SECTION .text

open_file:
enter 0,0
mov ebx, [ebp + 8] ; file handle
mov edx, [ebp + 12] ; file mode
push edx
push ebx
call fopen
leave
ret 8

read_file:
enter 0,0

mov ebx, [ebp + 8]
mov ecx, [ebp + 12]
mov edx, [ebp + 16]
push edx
push ecx
push ebx
call fscanf
leave
ret 12

main:
push ebp
mov ebp, esp
cmp dword [ebp + 8], 2
jnz usage
mov eax, [ebp + 12]
mov ebx, [eax + 4]
push file_mode
push ebx
call open_file
cmp eax, 0
jbe error
mov [file_handle], eax ;save the file handle

xor ecx, ecx
.L1:
mov eax, buffer
push eax
mov eax, scan_fmt
push eax
mov eax, [file_handle]
push eax
call read_file
cmp eax, -1 ; EOF returned?
je close_file
mov ecx, [buffer] ; first integer in file is count
.L2:

mov eax, buffer
push eax
mov eax, scan_fmt
push eax
mov eax, [file_handle]
push eax
call read_file
cmp eax, -1
je close_file
mov edx, [buffer]


;push buffer
;call printf
;add esp, 4
loop .L2



error:
push error_str
call printf
sub esp, 4
jmp exit
usage:
push usage_str
call printf
sub esp, 4
jmp exit

close_file:
push dword [file_handle]
call fclose
add esp, 4
exit:
mov esp, ebp
pop ebp
ret
 

Offline cerberus

  • Jr. Member
  • *
  • Posts: 2
Re: populating an array from a file
« Reply #1 on: October 25, 2012, 08:23:13 PM »
Took me a little time but I figured it out. Thanks anyway.