Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to partially read input until a new line using read()?

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading