Course Content
Programming in C
About Lesson

Input and output uses read and write system calls, which can be accessed using read and write functions from a C program.

ssize_t read(int fd, void *buf, size_t n);
ssize_t write(int fd, void *buf, size_t n);

Both accept a file descriptor as the first argument. The second argument is a void pointer to a buffer where the data is either read into or written from. The third argument contains the number of bytes. size_t is an unsigned integer whereas ssize_t is a signed integer.

Both the functions return number of bytes read / written. A return value of 0 represents end of file, -1 indicates error. For writing, a return value different from the number requested may suggest error.

Typical values of number of bytes are 1 (one character at a time), 1024 or 4096. Larger sizes will be more efficient because fewer system calls will be made.

#include <unistd.h>

#define BUFSIZE 1024

int main()
{
  char buffer[BUFSIZE];
  int n;
 
  while((n = read(0, buffer, BUFSIZE)) > 0)
    write(1, buffer, n); 
  return 0;
}

In the above program, we read input from standard input (file descriptor 0) and write it to standard output (file descriptor 1). We need to include header file to use read and write.

Scroll to Top