1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * Ported to LTP: Wayne Boyer
5 */
6
7 /*
8 * 1. creat() a file using 0444 mode, write to the fildes, write
9 * should return a positive count.
10 *
11 * 2. creat() should truncate a file to 0 bytes if it already
12 * exists, and should not fail.
13 *
14 */
15
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20
21 #include "tst_test.h"
22
23 static char filename[40];
24 static int fd;
25
setup(void)26 static void setup(void)
27 {
28 sprintf(filename, "creat01.%d", getpid());
29 }
30
31 static struct tcase {
32 int mode;
33 } tcases[] = {
34 {0644},
35 {0444}
36 };
37
verify_creat(unsigned int i)38 static void verify_creat(unsigned int i)
39 {
40 struct stat buf;
41 char c;
42
43 fd = SAFE_CREAT(filename, tcases[i].mode);
44
45 SAFE_STAT(filename, &buf);
46
47 if (buf.st_size != 0)
48 tst_res(TFAIL, "creat() failed to truncate file to 0 bytes");
49 else
50 tst_res(TPASS, "creat() truncated file to 0 bytes");
51
52 if (write(fd, "A", 1) != 1)
53 tst_res(TFAIL | TERRNO, "write was unsuccessful");
54 else
55 tst_res(TPASS, "file was created and written to successfully");
56
57 if (read(fd, &c, 1) != -1)
58 tst_res(TFAIL, "read succeeded unexpectedly");
59 else
60 tst_res(TPASS | TERRNO, "read failed expectedly");
61
62 SAFE_CLOSE(fd);
63 }
64
cleanup(void)65 static void cleanup(void)
66 {
67 if (fd > 0)
68 SAFE_CLOSE(fd);
69 }
70
71 static struct tst_test test = {
72 .tcnt = 2,
73 .test = verify_creat,
74 .needs_tmpdir = 1,
75 .cleanup = cleanup,
76 .setup = setup,
77 };
78