]>
git.saurik.com Git - apple/xnu.git/blob - SETUP/replacecontents/replacecontents.c
2 * Copyright (c) 2013 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
34 #include <sys/fcntl.h>
35 #include <sys/param.h>
40 int main(int argc
, char * argv
[])
43 char *newcontent
= NULL
;
44 size_t newcontentlength
= 0;
45 char *oldcontent
= NULL
;
48 const char *dst
= NULL
;
49 ssize_t readsize
, writesize
;
58 for (i
=2; i
< argc
; i
++) {
59 newcontentlength
+= strlen(argv
[i
]) + 1 /* space or newline */;
61 newcontentlength
+= 1; /* NUL */
63 newcontent
= malloc(newcontentlength
);
64 if (newcontent
== NULL
)
65 err(EX_UNAVAILABLE
, "malloc() failed");
69 for (i
=2; i
< argc
; i
++) {
70 strlcat(newcontent
, argv
[i
], newcontentlength
);
72 strlcat(newcontent
, " ", newcontentlength
);
74 strlcat(newcontent
, "\n", newcontentlength
);
78 dstfd
= open(dst
, O_RDWR
| O_CREAT
| O_APPEND
, DEFFILEMODE
);
80 err(EX_NOINPUT
, "open(%s)", dst
);
82 ret
= fstat(dstfd
, &sb
);
84 err(EX_NOINPUT
, "fstat(%s)", dst
);
86 if (!S_ISREG(sb
.st_mode
))
87 err(EX_USAGE
, "%s is not a regular file", dst
);
89 if (sb
.st_size
!= newcontentlength
) {
90 /* obvious new content must be different than old */
94 oldcontent
= malloc(newcontentlength
);
95 if (oldcontent
== NULL
)
96 err(EX_UNAVAILABLE
, "malloc(%lu) failed", newcontentlength
);
98 readsize
= read(dstfd
, oldcontent
, newcontentlength
);
100 err(EX_UNAVAILABLE
, "read() failed");
101 else if (readsize
!= newcontentlength
)
102 errx(EX_UNAVAILABLE
, "short read of file");
104 if (0 == memcmp(oldcontent
, newcontent
, newcontentlength
)) {
105 /* binary comparison succeeded, just exit */
109 err(EX_UNAVAILABLE
, "close() failed");
115 ret
= ftruncate(dstfd
, 0);
117 err(EX_UNAVAILABLE
, "ftruncate() failed");
119 writesize
= write(dstfd
, newcontent
, newcontentlength
);
121 err(EX_UNAVAILABLE
, "write() failed");
122 else if (writesize
!= newcontentlength
)
123 errx(EX_UNAVAILABLE
, "short write of file");
127 err(EX_NOINPUT
, "close(dst)");
134 fprintf(stderr
, "Usage: %s <dst> <new> <contents> <...>\n",