I've got a task to create a readline() function that would have the exact same behavior as read():
ssize_t read(int fd, void *buf, size_t count); (man read)
So it should return -1 on error and number of bytes read on success. Also, if the function receives a string with multiple \n chars, it should return only the first line and store the rest for a future use.
I was scrolling through this article: Reading a line ending with a newline character from a file descriptor
But I do not think the author had the same purpose - that is to work just as read()
I came up with this function:
//global buffer
char gBUF[BUFSIZ];
int readline2(int fd, char* buf){
static char* resultBuffer = gBUF;
int ret, mv;
char temp[256];
char* t;
bzero(temp, sizeof(temp));
t = strchr(resultBuffer,'\n');
if(t != NULL){
mv = t-resultBuffer+1;
strncpy(temp,resultBuffer, mv);
resultBuffer = resultBuffer + mv;
temp[strlen(temp)] = '\0';
strcpy(buf,temp);
bzero(temp, sizeof(temp));
ret = read(fd,&temp,256);
temp[ret]='\0';
strcat(resultBuffer,temp);
return mv;
}
ret = read(fd,&temp,256);
temp[ret]='\0';
t = strchr(temp,'\n');
mv = t-temp+1;
strncpy(buf,temp,mv);
strcat(resultBuffer,temp+mv);
return ret;
}
and I mean, it works well, although I had some real struggles with pointers and copying addresses instead of values.
My question is, how to improve this? I still have a feeling there's something missing or that something could significantly improve it.
I guess I should put a while inside and check whether the read string actually has a \n char and only return when it does, right?
I also do not like the idea of a global buffer, maybe I should just create a class/struct, something like this:
struct {
char BUF[BUFSIZ];
char *p = BUF;
}dataStruct;
to store the buffer and a pointer to it, but I do not really know how I could use that properly
Thanks for any suggestions!
Reading max 256bytes is a purpose, that should be the max;
I could've probably added that this function is to be used after in a multiprocess/multithread client server project. The server reads these lines from clients and should know what input came first, in what order the lines came, etc. The buffer should essentially work as a queue.
t
inmv = t-temp+1;
is not initialized. UB it is. What is the purpose of this line anyway? \$\endgroup\$