Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m trying to write a new version of the fdopen() and fgetc() routines replacin

ID: 3546025 • Letter: I

Question

I'm trying to write a new version of the fdopen() and fgetc() routines replacing
the regular routines found in <stdio.h> with my alternative code.

I have started the general outline below... and needs to be fleshed out.


In mygetc() - it should only call read() when the buffer is empty and it must

read blocks of characters into the buffer that always keep the OS file

position an aligned multiple of the buffer size.


I'm trying to write a new version of the fdopen() and fgetc() routines replacing I have started the general outline below... and needs to be fleshed out. In mygetc() - it should only call read() when the buffer is empty and it must read blocks of characters into the buffer that always keep the OS file position an aligned multiple of the buffer size. the regular routines found in with my alternative code.

Explanation / Answer

#include <unistd.h>

#include <stdio.h>   

#include <stdlib.h>

#include <stdbool.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>


struct myfile {

int fd;

int pos;

int size;

int count;

char * buf;

};


typedef struct myfile MYFILE;


MYFILE * myfdopen( int fd, const char * mode ) {

MYFILE * f;

if (fd < 0) {

return NULL;

}

f = (MYFILE*)malloc(sizeof(MYFILE));

f->size = 8;

f->pos = 0;

f->count = 0;

f->buf = (char*)malloc(f->size);

f->fd = fd;

return f;

}


void myfclose( MYFILE * f ) {

close (f->fd);

free (f->buf);

free (f);

}


char mygetc ( MYFILE * f ) {

char c;

if (f->count <= 0 || f->pos >= f->count) {

f->count = read (f->fd, f->buf, f->size);

if (f->count <= 0) {

return EOF;

}

else {

f->pos = 0;

}

}

  

c = f->buf[f->pos];

f->pos++;

  

return c;

}


/* test program, try to open test.txt */

int main() {

int fd = open("test.txt", O_RDONLY);

MYFILE* file = myfdopen(fd, "r");

char ch = mygetc(file);

  

while (ch != EOF) {

printf("%c", ch);

ch = mygetc(file);

}

  

myfclose(file);

  


return 0;

}