Our assignment is to make a simplified stdio.h. I have most of it done and working, but I am having a problem with with my_fwrite. I am trying to copy the buffer that the user sends to me into the stream's buffer. I figured that I would just copy 1 byte at a time, using their size as an indicator on when to stop copying. Is there a better way to do this? (like copy a certain amount of bytes into my buffer all at once?) Im sure there is a way, but not quite certian on how to go about it. The way I am doing it isnt working, as I am getting the following errors/warnings. (BTW, this has to be done on a *nix system, so done on a linux gcc compiler.)
gcc -O2 -Wall -pedantic -ansi -std=c99 -c -o my_fwrite.o my_fwrite.c
my_fwrite.c: In function 'my_fwrite':
my_fwrite.c:26: warning: dereferencing 'void *' pointer
my_fwrite.c:26: error: void value not ignored as it ought to be
my_fwrite.c:31: error: invalid lvalue in assignment
make: *** [my_fwrite.o] Error 1
Here is the relevant code :
Code:
typedef struct {
char *buf; /* pointer to buffer */
int fd; /* file descriptor */
int nbuf; /* size of buffer */
char *first; /* pointer to first character position */
char *last; /* pointer to last + 1 character position */
int status; /* see flags above */
} MY_FILE;
size_t my_fwrite(const void *ptr, size_t size, size_t nitems, MY_FILE *stream) {
if((stream->status & MY_IOWRT) == 2) {
int i = 0;
int j = 0;
while(i <= nitems) {
if((int)stream->last == ((int)stream->nbuf + (int)stream->buf)) { //If buffer is full, write out buffer.
int write_return;
write_return = write(stream->fd, stream->buf, stream->nbuf);
if(write_return == -1) {
return i;
}
stream->first = stream->buf;
stream->last = stream->buf;
}
while(j <= size) {
*stream->last = (unsigned char)*ptr;
j++;
}
j = 0;
stream->last = stream->last + size;
(int)ptr = (int)ptr + size;
i++;
}
return i - 1;
}
return MY_EOF;
}