add more test (3)
[cmore.git] / cmd.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #include "debug.h"
6
7 #include "cmd.h"
8
9 #define BUFFERSIZE 4096
10
11 static char *_read_stream (FILE *sd)
12 {
13 char *buffer = NULL;
14 size_t size = 0;
15 do {
16 size += BUFFERSIZE + (size == 0);
17 buffer = (char *) realloc (buffer, size);
18 memset (buffer + size - BUFFERSIZE - 1, 0, BUFFERSIZE + 1);
19 fread (buffer + size - BUFFERSIZE - 1, 1, BUFFERSIZE, sd);
20 } while (!feof (sd));
21
22 /* check size */
23 if (buffer[0] == '\0') {
24 free (buffer);
25 buffer = NULL;
26 }
27
28 return buffer;
29 }
30
31 char *exec_cmd (char *cmd)
32 {
33 int status = -1;
34 char *buffer = NULL;
35
36 VERBOSE (DEBUG, fprintf (stdout, "exec command: %s\n", cmd));
37 FILE *fp = popen (cmd, "r");
38 if (fp != NULL) {
39 buffer = _read_stream (fp);
40 status = pclose(fp);
41 }
42
43 if ((status == -1) || (buffer == NULL)) {
44 free (buffer);
45 buffer = NULL;
46 }
47
48 return buffer;
49 }
50
51 char *load_file (char *name)
52 {
53 int status = -1;
54 char *buffer = NULL;
55
56 VERBOSE (DEBUG, fprintf (stdout, "open file: %s\n", name));
57 FILE *fd = fopen (name, "r");
58 if (fd != NULL) {
59 buffer = _read_stream (fd);
60 status = fclose (fd);
61 }
62
63 if (status == -1) {
64 free (buffer);
65 buffer = NULL;
66 }
67
68 return buffer;
69 }
70
71 char *read_stdin (void)
72 {
73 char *buffer = NULL;
74
75 VERBOSE (DEBUG, fprintf (stdout, "read stdin\n"));
76 buffer = _read_stream (stdin);
77
78 return buffer;
79 }
80
81 char **split_lines (char *buffer, int max)
82 {
83 int n = 0;
84
85 char **lines = NULL;
86 int i, j;
87 char *line = (char *) calloc (max + 1, sizeof (char));
88 for (i = j = 0; buffer[i] != '\0'; i++) {
89 if (buffer[i] >= ' ') {
90 line[j++] = buffer[i];
91 }
92 if ((j == max) || (buffer[i] == '\n')) {
93 lines = (char **) realloc (lines, (n + 2) * sizeof (char *));
94 lines[n] = line;
95 lines[n + 1] = NULL;
96 line = calloc (max + 1, sizeof (char));
97 n++;
98 j = 0;
99 }
100 }
101 if (line[0] != '\0') {
102 lines = (char **) realloc (lines, (n + 2) * sizeof (char *));
103 lines[n++] = line;
104 } else {
105 free (line);
106 }
107 VERBOSE (DEBUG, fprintf (stdout, "split lines: %d\n", n));
108
109 return lines;
110 }
111
112 void free_lines (char **lines)
113 {
114 int i = 0;
115
116 while (lines[i]) {
117 free (lines[i++]);
118 }
119 free (lines);
120 }
121
122 /* vim: set ts=4 sw=4 et: */