gpt4 book ai didi

c - 读入用 C 打开的 MIPS 文件

转载 作者:行者123 更新时间:2023-12-03 22:52:09 24 4
gpt4 key购买 nike

我有一个 c 函数,我可以在其中打开和关闭文件。但我想用 MIPS 中实现的自定义 readFile 函数替换 fgets 函数。

根据:When reading file in MIPS, it reads last line twicehttp://courses.missouristate.edu/kenvollmar/mars/help/syscallhelp.html我需要将代码 14 传递给系统调用;和文件描述符、输入缓冲区的地址和作为参数读取的最大字符数。

在 c 中打开文件时,我得到一个 FILE*,从中我使用 fileno 得到一个 fileDescriptor(根据此 How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?)。

问题是系统调用似乎没有被执行。缓冲区保持不变,甚至返回寄存器 (v0) 的值为 14(相同代码),而不是读取的字符数。

用于调用系统调用的 MIPS 代码是:

li      v0, 14       # system call for read from file
lw a0, 40($fp) # file descriptor
lw a1, 32($fp) # address of buffer to which to read
lw a2, 36($fp) # buffer length
syscall # read from file

有什么问题吗?谢谢

最佳答案

我终于可以解决这个问题了。碰巧系统调用代码不是 14,而是 3(SYS_read 宏)。

readFile.S中读取的代码是:

li      v0, SYS_read       # system call for read from file
lw a0, 40($fp) # file descriptor
lw a1, 32($fp) # address of buffer to which to read
lw a2, 36($fp) # buffer length
syscall # read from file

第一个参数是文件描述符,不是文件指针。所以我从 main.c 中调用我的自定义 readFile 函数,如下所示:

FILE *fp;
fp = fopen("test-files/test.txt", "r");
int fileDescriptor = fileno(fp);
int bufIncrSize = 10;
char *buffer = (char*) malloc(bufIncrSize);
while (readFile(buffer, bufIncrSize, fileDescriptor)) {
printf("%s",buffer);
}

免责声明:此代码是不完整的,无法替换 fgets:

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

SYS_read 系统调用不会在换行符处停止,因此它可以读取多行。因此,您应该自己实现此行为。

关于c - 读入用 C 打开的 MIPS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444285/

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