Tests for module pwrite.
[gnulib.git] / tests / test-pwrite.c
1 /* Test the pwrite function.
2    Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 #include <unistd.h>
20
21 #include "signature.h"
22 SIGNATURE_CHECK (pwrite, ssize_t, (int, const void *, size_t, off_t));
23
24 #include <sys/types.h>
25 #include <fcntl.h>
26 #include <errno.h>
27
28 #include "macros.h"
29
30 #define N (sizeof buf - 1)
31
32 int
33 main (void)
34 {
35   char const *file = "out";
36   int fd;
37   char buf[] = "0123456789";
38   off_t pos = 2;
39   size_t i;
40   off_t init_pos;
41
42   ASSERT (file);
43
44   fd = open (file, O_CREAT | O_WRONLY, 0600);
45   ASSERT (0 <= fd);
46   ASSERT (write (fd, buf, N) == N);
47   ASSERT (close (fd) == 0);
48
49   fd = open (file, O_WRONLY, 0600);
50   ASSERT (0 <= fd);
51
52   init_pos = lseek (fd, pos, SEEK_SET);
53   ASSERT (init_pos == pos);
54
55   for (i = 0; i < N; i+=2)
56     {
57       const char byte = 'W';
58       ASSERT (pwrite (fd, &byte, 1, i) == 1);
59       ASSERT (lseek (fd, 0, SEEK_CUR) == init_pos);
60     }
61
62   {
63     /* Invalid offset must evoke failure with EINVAL.  */
64     const char byte = 'b';
65     ASSERT (pwrite (fd, &byte, 1, (off_t) -1) == -1);
66     ASSERT (errno == EINVAL);
67   }
68
69   ASSERT (close (fd) == 0);
70
71   {
72     char read_buf[N];
73     fd = open (file, O_RDONLY);
74     ASSERT (0 <= fd);
75     ASSERT (read (fd, buf, N) == N);
76     ASSERT (close (fd) == 0);
77     ASSERT (strcmp ("W1W3W5W7W9",buf) == 0);
78   }
79   return 0;
80 }