Featured Post

Trie implementation in C

Vector Write in C

Simple implementation of vector writes in unix. This example uses writev system call to write into a file. The writev call enables you to write multiple discontiguous regions of memory to a file descriptor in a single operation.This is called a vector write.

We use iovec structure for the purpose of filling up the vector.Each
element specifies one region of memory to write; the fields iov_base and iov_len
specify the address of the start of the region and the length of the region, respectively.

This program takes command line arguments to fill up the vector.
Anything after the second argument will go to the file.

//vector-write.c
//To compile : gcc -o vwrite vector-write.c
//To run : ./vwrite file-name argument1 argument2 ..

#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
int main (int argc, char* argv[])
{
  int fd;
  struct iovec* vec;
  struct iovec* vec_next;
  int i;
  
  if(argc < 2 )
  {
    printf("\nUsage : %s <filename> [args...]\n",argv[0]);
    exit(1);
  }
  
  char newline = '\n';
  
  char* filename = argv[1];
  
  argc -= 2;
  argv += 2;
  
  /* Allocate an array of iovec elements. We.ll need two for each
   * element of the argument list, one for the text itself, and one for
   * a newline. */
  
  vec = (struct iovec*) malloc (2 * argc * sizeof (struct iovec));
  
  /* Fill the iovec entries. */
  
  vec_next = vec;
  for (i = 0; i < argc; ++i) {
    
    /* The first element is the text of the argument itself. */
    
    vec_next->iov_base = argv[i];
    vec_next->iov_len = strlen (argv[i]);
    ++vec_next;
    
    /* The second element is a single newline character. It.s okay for
     * multiple elements of the struct iovec array to point to the
     * same region of memory. */
    
    vec_next->iov_base = &newline;
    vec_next->iov_len = 1;
    ++vec_next;
  }
  
  /* Write the to a file. */
  
  fd = open (filename, O_WRONLY | O_CREAT);
  writev (fd, vec, 2 * argc);
  close (fd);
  free (vec);
  return 0;
}

Comments