c - 在汇编中写一个 fopen 函数

标签 c file fopen inline-assembly turbo-c++

我正在尝试在 Turbo C++ 3.0 中实现 fopen,我需要在 asm 内联中编写它。

我写了一个代码,但是(不出意外......)它不起作用(编译失败)。

代码在这里:

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <stdlib.h>

int my_fopen_w(char fname[])
{
    int fd;
    char status;
    status = 'w'; // I need to write to a file and delete previous content
    asm{
        mov bl, status
        xor bh,bh
        push bp
        mov bp, sp
        push bx
        push fname
        //Same as fopen now fopen(file path= fname, "w" = bx)
        call _fopen
        add sp,8

        // Returned value in AX register 
        mov fd, ax  // That line may be incorrect, my teacher demands an Integer returned value  

    }
    return fd;
}

我收到一个错误:turbo c 无法识别 _fopen 调用。

Error with "call _fopen"

Error with "call fopen" 感谢您的帮助。

海姆

最佳答案

这似乎是 Turbo C 3.0 中的错误。 TCC 3.0 默认将 C 库链接到 CODE 段,因此您可以使用 C 函数的地址加载 AX(不需要下划线),然后使用 CALL AX:

#include <stdio.h>

int main ( void )
{
    char fname[] = "noname.txt";
    char status[] = "wb";
    FILE * fd;
    asm{
        lea ax, status
        push ax
        lea ax, fname
        push ax

        lea ax, fopen
        call ax

        pop cx
        pop cx
        mov fd, ax
    }
    return 0;
}

请注意:fopen 需要两个指向两个字符串的指针。这两个指针在编译时都是未知的。所以你必须在运行时使用 LEA 来获取它们,除非其他人(操作系统、C 启动代码等)已经为你获取了指针:

#include <stdio.h>

FILE*  my_fopen_w(char fname[])
{
    FILE * fd;
    char  status[]="wt";
    int my_fd;

    asm{
        lea ax, status
        push ax
        mov ax, fname               // fname was passed as a pointer ("Call by value")
        push ax

        lea ax, fopen
        call ax

        pop cx
        pop cx
        mov fd, ax
    }
    return fd;
}

int main(int argc, char *argv[])
{

  FILE * fd;

  fd = my_fopen_w(argv[1]);         // argv[1] is a pointer to a string
  fputs("Here I am.", fd);
  fclose(fd);

  return 0;

}

关于c - 在汇编中写一个 fopen 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51981756/

相关文章:

C fork 和 pipe 多进程

c - 如何链接三个连续内存块

c - 函数调用中不兼容的指针类型 - C

html - 输入类型=文件 "Accept"属性在 Chrome 中不起作用?

c - 尝试读取宽字符会给出 EOF

c - 这个死锁隐藏在哪里?

file - 将矩阵写入文件,没有标题和行号

HTML - 像 Web 浏览器通常那样加载图像

php-5.3 - 为什么 PHP fopen + fwrite 会出现双文档?

C:打开的文件太多