Read in MIPS file opened in C

I have a c function where I open and close a file. But I want to replace the fgets function with a custom readFile function implemented in MIPS.

According to: When reading a file in MIPS, it reads the last line twice and http://courses.missouristate.edu/kenvollmar/mars/help/syscallhelp.html I need to pass syscall code 14; and a file descriptor, input buffer address, and maximum number of characters to read as arguments.

When I open a file in ci, get FILE * from which I get fileDescriptor using fileno (according to this How do I convert a file pointer (FILE * fp) to a file descriptor (int fd)? ).

The problem is syscall is not executing. The buffer remains unchanged, and even the return register (v0) is set to 14 (same code) instead of the number of characters read.

MIPS code used to invoke the system call:

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

      

What could be wrong? Thanks to

+3


source to share


1 answer


I could finally work it out. It happens that the syscall code was not 14, but 3 (SYS_read macro).

Code in readFile.S for reading:

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

      

the first parameter is a file descriptor, not a file pointer. So I call my custom readFile function from main.c like this:



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);
}

      

Disclaimer: This code is incomplete for a replacement for fgets, which does:

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

the SYS_read system call does not stop at the newline character, so it can read more than one line. So, you have to implement this beahivour yourself.

+1


source







All Articles