UNIX read and write system calls sample program in C

By: Tamil Selvan Emailed: 1598 times Printed: 2044 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Input and output uses the read and write system calls, which are accessed from C programs through two functions called read and write. For both, the first argument is a file descriptor. The second argument is a character array in your program where the data is to go to or to come from. The third argument is the number is the number of bytes to be transferred.
   int n_read = read(int fd, char *buf, int n);
   int n_written = write(int fd, char *buf, int n);
Each call returns a count of the number of bytes transferred. On reading, the number of bytes returned may be less than the number requested. A return value of zero bytes implies end of file, and -1 indicates an error of some sort. For writing, the return value is the number of bytes written; an error has occurred if this isn't equal to the number requested.

Any number of bytes can be read or written in one call. The most common values are 1, which means one character at a time (``unbuffered''), and a number like 1024 or 4096 that corresponds to a physical block size on a peripheral device. Larger sizes will be more efficient because fewer system calls will be made.

Putting these facts together, we can write a simple program to copy its input to its output. This program will copy anything to anything, since the input and output can be redirected to any file or device.

   #include "syscalls.h"

   main()  /* copy input to output */
   {
       char buf[BUFSIZ];
       int n;

       while ((n = read(0, buf, BUFSIZ)) > 0)
           write(1, buf, n);
       return 0;
   }
We have collected function prototypes for the system calls into a file called syscalls.h so we can include it in the programs of this chapter. This name is not standard, however.

The parameter BUFSIZ is also defined in syscalls.h; its value is a good size for the local system. If the file size is not a multiple of BUFSIZ, some read will return a smaller number of bytes to be written by write; the next call to read after that will return zero.

It is instructive to see how read and write can be used to construct higher-level routines like getchar, putchar, etc. For example, here is a version of getchar that does unbuffered input, by reading the standard input one character at a time.

   #include "syscalls.h"

   /* getchar:  unbuffered single character input */
   int getchar(void)
   {
       char c;

       return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
   }
c must be a char, because read needs a character pointer. Casting c to unsigned char in the return statement eliminates any problem of sign extension.

The second version of getchar does input in big chunks, and hands out the characters one at a time.

   #include "syscalls.h"

   /* getchar:  simple buffered version */
   int getchar(void)
   {
       static char buf[BUFSIZ];
       static char *bufp = buf;
       static int n = 0;

       if (n == 0) {  /* buffer is empty */
           n = read(0, buf, sizeof buf);
           bufp = buf;
       }
       return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
   }
If these versions of getchar were to be compiled with <stdio.h> included, it would be necessary to #undef the name getchar in case it is implemented as a macro.

C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

nice explanation.I want to write contents of file on the port.will you please help me about it.I am getting confused,When i use write,read sys calls.how to access file content when i use 1 descriptor for opening port and 1 descriptor for opening file.

View Tutorial          By: aparna at 2013-02-05 13:17:36

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Tamil Selvan
Inner Class Example in Java
PreparedStatement Example in Java
UNIX read and write system calls sample program in C
Pointer Arrays and Pointers to Pointers in C
Relational and Logical Operators in C
Arithmetic Operators in C
strlen() sample program in C++
Sample program to draw a arc in J2ME
What Java Has Removed from C++
FileReader and FileWriter example program in Java

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
UNIX read and write system calls sample program in C
Constants and escape sequences in C
A Storage Allocator sample program in C
ERRNO.H Header File in C
Passing double value to a function in C
Printing a simple histogram in C
Getting Started with C
File Copying in C
Pointers and Arrays in C
Address Arithmetic and pointers in C
Table Lookup - hashtab - example program in C
fgets(), fputs() - Line Input and Output - sample program in C
Using realloc() Function in C
Using free() Function in C
Most Emailed Articles (in C)
Conditional Expressions in C
fgets(), fputs() - Line Input and Output - sample program in C
Symbolic Constants using #define in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Address Arithmetic and pointers in C
Character Pointers and Functions in C
Initialization of Pointer Arrays in C
Pointers to Structures example program in C
Using printf function in C
A Storage Allocator sample program in C
Using free() Function in C
The C Character Set
Writing The First C program
Formatting with printf in C
while, do while and for loops in C