aboutsummaryrefslogtreecommitdiffstats
path: root/swab_testf.c
blob: fa552301161af06b4156dfb8f25416a631d414df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * This program reads a list of pathnames from standard input,
 * and prints out a list of those pathnames that are either
 * regular files or symbolic links.
 *
 * If a line begins with "# ", the rest of the line is taken
 * to be a name of an output file.  All output will then go to
 * that file, until another "# " line is found, at which point
 * the previous file is closed and a new file is opened for output.
 * Empty output files are removed.
 */
#include <stdio.h>
#include <stdlib.h>
#include <err.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <string.h>

#define FILENAME_LEN 4096

int
main(int argc, char *argv[])
{
	char file_name[FILENAME_LEN];
	char pkg_name[FILENAME_LEN];
	struct stat stb;
	FILE *fout = stdout;
	int nfiles = 0;

	pkg_name[0] = '\0';
	while (fgets(file_name, sizeof(file_name), stdin) != NULL) {
		/* Zap the trailing newline */
		file_name[strlen(file_name)-1] = '\0';

		/* Check for package name */
		if (file_name[0] == '#' && file_name[1] == ' ') {
			if (fout != stdout) {
				fclose(fout);
				/* Remove empty files */
				if (pkg_name[0] && nfiles == 0)
					(void)unlink(pkg_name);
			}
			strncpy(pkg_name, &file_name[2], FILENAME_LEN);
			fout = fopen(pkg_name, "w");
			if (fout == NULL) {
				warn("%s", pkg_name);
				pkg_name[0] = '\0';
			}
			nfiles = 0;
			continue;
		}
		if (stat(file_name, &stb) == 0 &&
		    (S_ISREG(stb.st_mode) || S_ISLNK(stb.st_mode))) {
			fprintf(fout, "%s\n", file_name);
			nfiles++;
		}
	}
	if (fout != stdout)
		fclose(fout);
	exit (0);
}