I'm trying to partially read input until a new line is inputed "\n". But how can I do that with the read() function? Right now I've made the partial read until the terminal interface is logged out and the input is stopped (pressing ctrl d on linux terminal), but don't know how to make it stop when a new line is inputted. Here is my code:
int fd = 0;
const size_t read_size = 100;
size_t size = read_size;
char *buff = malloc(size 1);
size_t offset = 0;
size_t res = 0;
while((res = read(fd, buff offset, read_size)) > 0)
{
offset = res;
buff[offset] = '\0';
if (offset read_size > size)
{
size *= 2;
buff = realloc(buff, size 1);
}
}
return buff;
CodePudding user response:
I'm trying to partially read input until a new line is inputed "\n". But how can I do that with the read() function?
The only way you can achieve this with a read
is to read one character at a time. Once you've read the '\n'
character, stop.
how do I check what is being read?
while (read(fd, buf offset, 1) == 1) {
if (buf[offset] == '\n') break;
offset = 1;
}