-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfold-line.c
104 lines (84 loc) · 2.4 KB
/
fold-line.c
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
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* It splits a long lines into multiple line according to max limit per line.
*/
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80
#define BUFFERSIZE 1024
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]\n");
}
int main(int argc, char *argv[]) {
int c;
int maxline = MAXLINE;
int count = 0;
int bufferUsed = 0;
char buffer[BUFFERSIZE + 1] = {'\0'};
programName = basename(argv[0]);
while ((c = getopt(argc, argv, "m:")) != -1) {
switch (c) {
case 'm':
maxline = strtol(optarg, NULL, 0);
break;
case '?':
case 'h':
printHelp();
exit(1);
}
}
while ((c = getchar()) != EOF) {
if (bufferUsed < maxline) {
buffer[bufferUsed++] = c;
buffer[bufferUsed] = '\0';
} else {
char *cptr = &buffer[bufferUsed - 1];
while (' ' != *cptr && cptr != buffer)
cptr--;
// the line input so far has no space, so we print everything out.
if (buffer == cptr) {
// I was taught to put variable definition before executable statement
// in function block, but there will be time that I do not want to do
// that when the variable definition is used so locally.
for (int i = 0; i < bufferUsed; i++)
putchar(buffer[i]);
bufferUsed = 0;
buffer[bufferUsed] = '\0';
} else // the line input has space, so we print the line until space, and
// then continue to build up line.
{
char *iter = buffer;
while (iter != cptr) {
putchar(*iter);
iter++;
}
iter = buffer;
cptr++;
while (cptr != &buffer[bufferUsed]) {
*iter = *cptr;
iter++;
cptr++;
}
*iter = '\0';
bufferUsed = iter - buffer + sizeof(buffer[0]);
putchar('\n');
}
buffer[bufferUsed++] = c;
buffer[bufferUsed] = '\0';
} /* if ( bufferUsed < maxline ) ... else */
} /* while ( ( c = getchar() ) != EOF ) */
if (bufferUsed > 0) {
int i = 0;
while (i < bufferUsed) {
putchar(buffer[i]);
i++;
}
}
return 0;
}