1 | /* $Id: append.c 370 2005-12-18 03:48:02Z bird $ */
|
---|
2 | /** @file
|
---|
3 | *
|
---|
4 | * kMk Builtin command - append text to file.
|
---|
5 | *
|
---|
6 | * Copyright (c) 2005 knut st. osmundsen <[email protected]>
|
---|
7 | *
|
---|
8 | *
|
---|
9 | * This file is part of kBuild.
|
---|
10 | *
|
---|
11 | * kBuild is free software; you can redistribute it and/or modify
|
---|
12 | * it under the terms of the GNU General Public License as published by
|
---|
13 | * the Free Software Foundation; either version 2 of the License, or
|
---|
14 | * (at your option) any later version.
|
---|
15 | *
|
---|
16 | * kBuild is distributed in the hope that it will be useful,
|
---|
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
19 | * GNU General Public License for more details.
|
---|
20 | *
|
---|
21 | * You should have received a copy of the GNU General Public License
|
---|
22 | * along with kBuild; if not, write to the Free Software
|
---|
23 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
---|
24 | *
|
---|
25 | */
|
---|
26 |
|
---|
27 | #include <string.h>
|
---|
28 | #include <stdio.h>
|
---|
29 | #include "err.h"
|
---|
30 | #include "kmkbuiltin.h"
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * Appends text to a textfile, creating the textfile if necessary.
|
---|
34 | */
|
---|
35 | int kmk_builtin_append(int argc, char **argv, char **envp)
|
---|
36 | {
|
---|
37 | int i;
|
---|
38 | FILE *pFile;
|
---|
39 |
|
---|
40 | g_progname = argv[0];
|
---|
41 |
|
---|
42 | /*
|
---|
43 | * Open the output file.
|
---|
44 | */
|
---|
45 | if (argc <= 1)
|
---|
46 | {
|
---|
47 | errx(1, "missing filename!");
|
---|
48 | fprintf(stderr, "usage: append file [string ...]\n");
|
---|
49 | return 1;
|
---|
50 | }
|
---|
51 | pFile = fopen(argv[1], "a");
|
---|
52 | if (!pFile)
|
---|
53 | return err(1, "failed to open '%s'.", argv[1]);
|
---|
54 |
|
---|
55 | /*
|
---|
56 | * Append the argument strings to the file
|
---|
57 | */
|
---|
58 | for (i = 2; i < argc; i++)
|
---|
59 | {
|
---|
60 | const char *psz = argv[i];
|
---|
61 | size_t cch = strlen(psz);
|
---|
62 | if (i > 2)
|
---|
63 | fputc(' ', pFile);
|
---|
64 | fwrite(psz, 1, cch, pFile);
|
---|
65 | }
|
---|
66 |
|
---|
67 | /*
|
---|
68 | * Add the newline and close the file.
|
---|
69 | */
|
---|
70 | if ( fputc('\n', pFile) == EOF
|
---|
71 | || ferror(pFile))
|
---|
72 | {
|
---|
73 | fclose(pFile);
|
---|
74 | return errx(1, "error writing to '%s'!", argv[1]);
|
---|
75 | }
|
---|
76 | if (fclose(pFile))
|
---|
77 | return err(1, "failed to fclose '%s'!", argv[1]);
|
---|
78 | return 0;
|
---|
79 | }
|
---|
80 |
|
---|