Initial revision
[wmaker-crm.git] / util / wxcopy.c
blob674352abe44ab7f5e73d9844e4e173ff078c9f66
1 /* wxcopy.c- copy stdin or file into cutbuffer
2 *
3 * Copyright (c) 1997 Alfredo K. Kojima
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <X11/Xlib.h>
26 #define LINESIZE (4*1024)
27 #define MAXDATA (64*1024)
29 void
30 help(char *progn)
32 printf("usage: %s [-cutbuffer number] [filename]\n", progn);
35 static int
36 errorHandler(Display *dpy, XErrorEvent *err)
38 /* ignore all errors */
39 return 0;
42 int
43 main(int argc, char **argv)
45 Display *dpy;
46 int i;
47 int buffer=-1;
48 char *filename=NULL;
49 FILE *file=stdin;
50 char *buf=NULL;
51 int l=0;
53 for (i=1; i<argc; i++) {
54 if (argv[i][0]=='-') {
55 if (argv[i][1]=='h') {
56 help(argv[0]);
57 exit(0);
58 } else if (strcmp(argv[i],"-cutbuffer")==0) {
59 if (i<argc-1) {
60 i++;
61 if (sscanf(argv[i],"%i", &buffer)!=1) {
62 printf("%s: could not convert \"%s\" to int\n",
63 argv[0], argv[i]);
64 exit(1);
66 if (buffer<0 || buffer > 7) {
67 printf("%s: invalid buffer number %i\n", argv[0],
68 buffer);
69 exit(1);
71 } else {
72 help(argv[0]);
73 exit(1);
75 } else {
76 help(argv[0]);
77 exit(1);
79 } else {
80 filename = argv[i];
83 if (filename) {
84 file = fopen(filename, "r");
85 if (!file) {
86 char line[1024];
87 sprintf(line, "%s: could not open \"%s\"", argv[0], filename);
88 perror(line);
89 exit(1);
93 dpy = XOpenDisplay("");
94 XSetErrorHandler(errorHandler);
95 if (!dpy) {
96 printf("%s: could not open display\n", argv[0]);
97 exit(1);
99 if (buffer<0) {
100 XRotateBuffers(dpy, 1);
101 buffer=0;
103 while (!feof(file)) {
104 char *nbuf;
105 char tmp[LINESIZE+2];
106 int nl=0;
108 if (!fgets(tmp, LINESIZE, file)) {
109 break;
111 nl = strlen(tmp);
112 if (!buf)
113 nbuf = malloc(l+nl+1);
114 else
115 nbuf = realloc(buf, l+nl+1);
116 if (!nbuf) {
117 printf("%s: out of memory\n", argv[0]);
118 exit(1);
120 buf=nbuf;
121 if (l==0) {
122 strcpy(buf,tmp);
123 } else {
124 strcat(buf, tmp);
126 l+=nl;
127 if (l>=MAXDATA) {
128 printf("%s: too much data in input\n", argv[0]);
129 exit(1);
132 if (buf)
133 XStoreBuffer(dpy, buf, l, buffer);
134 XFlush(dpy);
135 XCloseDisplay(dpy);
136 exit(1);