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
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ellipsize(unsigned int length, char *string) {
int i;
int lastidx = -1;
char *retString;
if (strlen(string) > length) {
for (i = 0; i < length; i++) {
if (isspace(string[i])) {
lastidx = i;
}
}
if (lastidx == -1) {
lastidx = length;
}
retString = malloc((length + 4) * sizeof(char));
strncpy(retString, string, lastidx);
retString[lastidx] = '\0';
strcat(retString, "...");
} else {
retString = strdup(string);
}
return retString;
}
int main(int argc, char **argv) {
int i;
char *string;
unsigned int limit;
if (argc < 2) {
printf("Usage:\n");
printf("\t%s <LIMIT> [STRING]...\n", argv[0]);
} else {
if (!sscanf(argv[1], "%u", &limit)) {
printf("ERROR: Wrong LIMIT argument.\n");
exit(EXIT_FAILURE);
}
}
for (i = 2; i < argc; i++) {
string = strdup(argv[i]);
string[limit] = '\0';
printf("First %uchars (at most) from the input string: %s\n", limit, string);
free(string);
string = ellipsize(limit, argv[i]);
printf("Ellipsized string: %s\n", string);
free(string);
}
return 0;
}
|