gpt4 book ai didi

assembly - 使用 nasm 在程序集中调用 fscanf

转载 作者:行者123 更新时间:2023-12-04 06:28:08 25 4
gpt4 key购买 nike

我正在尝试从格式为整数字符空白整数的文件中读取 3 个值。例如:

5、3

在那精确格式即:5 后没有空格,逗号后有空格,3 后没有空格。

我成功调用 fopen 打开文件,并使用 fgetc 访问同一个文件并打印其内容。现在我正在尝试使用 fscanf()

我读到要从程序集中调用 C 函数,您必须以相反的顺序将参数推送到堆栈上,下面是我执行此操作的代码

    lea eax, [xValue]
push eax
lea eax, [comma]
push eax
lea eax, [yValue]
push eax
mov eax, [format] ;defined as [format db "%d %c %d", 0] in the data section
push eax
mov eax, ebx ; move handle to file into eax
push eax
call _fscanf

在这一点上,我假设以上等价于:
fscanf(fp, "%d %c %d", &yValue, &comma, &xValue);

如果它等价于上面,我如何访问读取的值?我知道我正在正确访问文件,因为我能够通过调用 fgetc 打印出单个字符,但为了清楚起见,下面是我打开文件的代码
    mov eax, fileMode
push eax
mov eax, fileName
push eax
call _fopen
mov ebx, eax ;store file pointer

非常感谢任何帮助/建议。谢谢。

编辑添加…

答案提供了解决方案。为遇到此问题的任何其他人发布下面的代码。
section .data

fname db "data.txt",0
mode db "r",0 ;;set file mode for reading
format db "%d%c %d", 0

;;--- end of the data section -----------------------------------------------;;

section .bss
c resd 1
y resd 1
x resd 1
fp resb 1

section .text
extern _fopen
global _main

_main:
push ebp
mov ebp,esp

mov eax, mode
push eax
mov eax, fname
push eax
call _fopen
mov [fp] eax ;store file pointer

lea eax, [y]
push eax
lea eax, [c]
push eax
lea eax, [x]
push eax
lea eax, [format]
push eax
mov eax, [fp]
push eax
call _fscanf

;at this point x, y and c has the data

mov eax,0
mov esp,ebp
pop ebp
ret

最佳答案

我认为您的 scanf() 格式字符串是错误的。应该是“%d%c %d”。你为什么要关心逗号呢?为什么不直接使用 "%d, %d"并抛弃逗号变量。

此外,您尝试使用 [format] 的第一个字节中的值加载 eax,您需要将指针推送到格式。

最后,您不希望内存地址周围有括号,除非您的汇编程序很奇怪您正在推送错误的地址。

lea eax, xvalue
push eax
lea eax, yValue
push eax
lea eax, format
push eax
call _fscanf

现在你应该在 xvalue 和 yvalue 中拥有你想要的值

关于assembly - 使用 nasm 在程序集中调用 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com