| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <fcntl.h> |
| 8 |
#include <stdlib.h> |
| 9 |
#include <sys/stat.h> |
| 10 |
#include <sys/types.h> |
| 11 |
#include <sys/uio.h> |
| 12 |
#include <unistd.h> |
| 13 |
|
| 14 |
int main (int argc, char* argv[]) |
| 15 |
{ |
| 16 |
int fd; |
| 17 |
struct iovec* vec; |
| 18 |
struct iovec* vec_next; |
| 19 |
int i; |
| 20 |
/* We'll need a "buffer" containing a newline character. Use an |
| 21 |
ordinary char variable for this. */ |
| 22 |
char newline = '\n'; |
| 23 |
/* The first command-line argument is the output filename. */ |
| 24 |
char* filename = argv[1]; |
| 25 |
/* Skip past the first two elements of the argument list. Element |
| 26 |
zero is the name of this program, and element one is the output |
| 27 |
filename. */ |
| 28 |
argc -= 2; |
| 29 |
argv += 2; |
| 30 |
|
| 31 |
/* Allocate an array of iovec elements. We'll need two for each |
| 32 |
element of the argument list, one for the text itself and one for |
| 33 |
a newline. */ |
| 34 |
vec = (struct iovec*) malloc (2 * argc * sizeof (struct iovec)); |
| 35 |
|
| 36 |
/* Loop over the argument list, building the iovec entries. */ |
| 37 |
vec_next = vec; |
| 38 |
for (i = 0; i < argc; ++i) { |
| 39 |
/* The first element is the text of the argument itself. */ |
| 40 |
vec_next->iov_base = argv[i]; |
| 41 |
vec_next->iov_len = strlen (argv[i]); |
| 42 |
++vec_next; |
| 43 |
/* The second element is a single newline character. It's OK for |
| 44 |
multiple elements of the struct iovec array to point to the |
| 45 |
same region of memory. */ |
| 46 |
vec_next->iov_base = &newline; |
| 47 |
vec_next->iov_len = 1; |
| 48 |
++vec_next; |
| 49 |
} |
| 50 |
|
| 51 |
/* Write the arguments to a file. */ |
| 52 |
fd = open (filename, O_WRONLY | O_CREAT); |
| 53 |
writev (fd, vec, 2 * argc); |
| 54 |
close (fd); |
| 55 |
|
| 56 |
free (vec); |
| 57 |
return 0; |
| 58 |
} |