BSD 4_1c_2 release
[unix-history] / usr / src / usr.bin / touch.c
CommitLineData
0219f737
KM
1#ifndef LINT
2static char *sccsid = "@(#)touch.c 4.2 (Berkeley) 82/06/09";
3#endif not LINT
4
5/*
6 * attempt to set the modify date of a file to the current date.
7 * if the file exists, read and write its first character.
8 * if the file doesn't exist, create it, unless -c option prevents it.
9 * if the file is read-only, -f forces chmod'ing and touch'ing.
10 */
11
7add65c5 12#include <stdio.h>
0219f737
KM
13#include <sys/types.h>
14#include <sys/stat.h>
15
16int dontcreate; /* set if -c option */
17int force; /* set if -f option */
7add65c5 18
0219f737 19char *whoami = "touch";
7add65c5
BJ
20
21main(argc,argv)
0219f737
KM
22 int argc;
23 char **argv;
7add65c5 24{
0219f737 25 char *argp;
7add65c5 26
0219f737
KM
27 dontcreate = 0;
28 force = 0;
29 for (argv++; **argv == '-'; argv++) {
30 for (argp = &(*argv)[1]; *argp; argp++) {
31 switch (*argp) {
32 case 'c':
33 dontcreate = 1;
34 break;
35 case 'f':
36 force = 1;
37 break;
38 default:
39 fprintf(stderr, "%s: bad option -%c\n",
40 whoami, *argp);
41 exit(1);
42 }
43 }
44 }
45 for (/*void*/; *argv; argv++) {
46 touch(*argv);
47 }
7add65c5
BJ
48}
49
0219f737
KM
50touch(filename)
51 char *filename;
7add65c5 52{
0219f737 53 struct stat statbuffer;
7add65c5 54
0219f737
KM
55 if (stat(filename,&statbuffer) == -1) {
56 if (!dontcreate) {
57 readwrite(filename,0);
58 } else {
59 fprintf(stderr, "%s: %s: does not exist\n",
60 whoami, filename);
61 }
7add65c5 62 return;
0219f737
KM
63 }
64 if ((statbuffer.st_mode & S_IFMT) != S_IFREG) {
65 fprintf(stderr, "%s: %s: can only touch regular files\n",
66 whoami, filename);
67 return;
68 }
69 if (!access(filename,4|2)) {
70 readwrite(filename,statbuffer.st_size);
71 return;
72 }
73 if (force) {
74 if (chmod(filename,0666)) {
75 fprintf(stderr, "%s: %s: couldn't chmod: ",
76 whoami, filename);
77 perror("");
78 return;
7add65c5 79 }
0219f737
KM
80 readwrite(filename,statbuffer.st_size);
81 if (chmod(filename,statbuffer.st_mode)) {
82 fprintf(stderr, "%s: %s: couldn't chmod back: ",
83 whoami, filename);
84 perror("");
85 return;
86 }
87 } else {
88 fprintf(stderr, "%s: %s: cannot touch\n", whoami, filename);
89 }
90}
7add65c5 91
0219f737
KM
92readwrite(filename,size)
93 char *filename;
94 int size;
95{
96 int filedescriptor;
97 char first;
7add65c5 98
0219f737
KM
99 if (size) {
100 filedescriptor = open(filename,2);
101 if (filedescriptor == -1) {
102error:
103 fprintf(stderr, "%s: %s: ", whoami, filename);
104 perror("");
105 return;
106 }
107 if (read(filedescriptor, &first, 1) != 1) {
108 goto error;
109 }
110 if (lseek(filedescriptor,0l,0) == -1) {
111 goto error;
112 }
113 if (write(filedescriptor, &first, 1) != 1) {
114 goto error;
115 }
116 } else {
117 filedescriptor = creat(filename,0666);
118 if (filedescriptor == -1) {
119 goto error;
120 }
7add65c5 121 }
0219f737
KM
122 if (close(filedescriptor) == -1) {
123 goto error;
7add65c5 124 }
7add65c5 125}