UNIX & GNU/Linux - System calls - Using read()

We are going to use the read() function to read on the standard input from our favorite shell.

So each time you will write something then type ENTER, the text written will be display on the shell.

Let's see this, with this tiny tutorial of the read() function with a C example.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#define BUF_SIZE         1024

void empty_buf(char *buf)
{
    int i;

    i = 0;
    while (buf[i])
    {
        buf[i] = '\0';
        ++i;
    }
    buf[i] = '\0';
}

int main(void)
{
    int gogogo;
    int fd;
    char *buf;

    buf = malloc(sizeof(*buf) * BUF_SIZE + 1);
    if (buf == NULL)
    {
        fprintf(stderr, "Error: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    fd = 0;
    gogogo = 1;
    while (gogogo)
    {
        read(fd, buf, BUF_SIZE);
        printf("buf = %s\n", buf);
        empty_buf(buf);
    }
    exit(EXIT_SUCCESS);
}
 
Good job. wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.