Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View strip_pipe_delimited_fields.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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
static char * append (char *field, size_t *size, size_t *len, char c);
static size_t get_field (char **field, size_t *size, FILE *file);
static char const * strip_field (char *field, size_t len);
 
static bool end_of_file = false;
static bool end_of_line;
 
int
main (int argc, char *argv [])
{
char *field = NULL;
FILE *file;
char const *filename;
size_t len;
size_t size = 0;
char const *stripped;
 
if (2 != argc) {
printf("Exactly one filename must be specified\n");
return EXIT_FAILURE;
}
 
filename = argv[1];
file = fopen(filename, "r");
if (NULL == file) {
printf("%s: file not found\n", filename);
return EXIT_FAILURE;
}
 
NEW_LINE:
len = get_field(&field, &size, file);
stripped = strip_field(field, len);
if (strcmp("", stripped)) {
printf("%s", stripped);
if (end_of_file) {
goto EXIT;
}
} else {
if (end_of_file) {
goto EXIT;
}
printf("null");
}
 
while (!end_of_line) {
len = get_field(&field, &size, file);
printf("|%s", strip_field(field, len));
if (end_of_file) {
goto EXIT;
}
}
 
printf("\n");
goto NEW_LINE;
 
EXIT:
free(field);
 
fclose(file);
 
return EXIT_SUCCESS;
}
 
char *
append (char *field, size_t *size, size_t *len, char c)
{
if (*size <= (*len + 1)) {
field = (char *)realloc(field, *size + 64);
*size += 64;
}
 
field[(*len)++] = c;
 
return field;
}
 
size_t
get_field (char **field, size_t *size, FILE *file)
{
int c;
size_t len = 0;
 
end_of_line = false;
c = fgetc(file);
while ('|' != c) {
if ('\n' == c) {
end_of_line = true;
goto EXIT;
}
if (EOF == c) {
end_of_file = true;
goto EXIT;
}
*field = append(*field, size, &len, c);
c = fgetc(file);
}
 
EXIT:
(*field)[len] = '\0';
 
return len;
}
 
char const *
strip_field (char *field, size_t len)
{
size_t b;
size_t e;
 
if (0 == len) {
return field;
}
 
for (b = 0; b < len; ++b) {
if ((' ' != field[b]) && ('\t' != field[b])) {
break;
}
}
 
for (e = len - 1; e > b; --e) {
if ((' ' != field[e]) && ('\t' != field[e])) {
break;
}
}
 
if (e == b) {
field[b] = '\0';
} else {
field[e + 1] = '\0';
}
 
return field + b;
}
 
// Local Variables:
// c-basic-offset: 4
// indent-tabs-mode: nil
// End:
 
// vi: set et ts=4 sw=4 :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.