-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfold-line.c
More file actions
117 lines (98 loc) · 2.69 KB
/
Copy pathfold-line.c
File metadata and controls
117 lines (98 loc) · 2.69 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* It splits a long line into multiple lines by splitting it at space and keep
* it to certain maximum characters per line with exception that if the whole
* line has no space, then it will not be split and will exceed the max number
* specified.
*/
#include <ctype.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80
char *programName = NULL;
void printHelp(void) {
fprintf(stderr, "%s [-h] [-m line]\n", programName);
fprintf(stderr, "\n");
fprintf(stderr, " -h : print this help message\n");
fprintf(stderr,
" -m line : number of character per line [default is 80 and maximum "
"is %d]\n",
BUFSIZ);
}
int main(int argc, char *argv[]) {
int c;
char buffer[BUFSIZ];
int maxline = MAXLINE;
programName = basename(argv[0]);
while ((c = getopt(argc, argv, "m:")) != -1) {
switch (c) {
case 'm':
maxline = strtol(optarg, NULL, 0);
if (maxline > sizeof(buffer)) {
printHelp();
exit(1);
}
break;
case '?':
case 'h':
printHelp();
exit(1);
}
}
int count = 0;
bool skipLeadingSpace = false;
while ((c = getchar()) != EOF) {
if (count < maxline) {
// accummulate characters for split when reach max number of characters
// but skip leading space if indicated by split in prior line.
if (skipLeadingSpace && isspace(c)) {
;
} else {
buffer[count++] = c;
skipLeadingSpace = false;
}
} else {
// print everything up to last space
// shift characters after last space to the front
// append new character
int lastSpaceIndex = count - 1;
if (!isspace(c)) {
while (lastSpaceIndex >= 0 && !isspace(buffer[lastSpaceIndex])) {
lastSpaceIndex--;
}
if (lastSpaceIndex < 0) {
lastSpaceIndex = count - 1;
}
}
int index = 0;
while (index <= lastSpaceIndex) {
putchar(buffer[index++]);
}
if (isspace(c) ||
(lastSpaceIndex < count && isspace(buffer[index - 1]))) {
putchar('\n');
skipLeadingSpace = isspace(c);
}
index = 0;
lastSpaceIndex++;
while (lastSpaceIndex < count) {
buffer[index++] = buffer[lastSpaceIndex++];
}
if (isspace(c)) {
count = 0;
} else {
buffer[index++] = c;
count = index;
}
}
} /* while ((c = getchar()) != EOF) */
// if it is end of input, print everything not yet print
for (int index = 0; index < count; index++) {
putchar(buffer[index]);
}
return 0;
}