7. Miscellaneous Utilties
7.1. Getline
The Sorg parser parses a file one line at a time.
Because the getline function is not part of the ANSI C standard, an implementation is used in it's place.
<<getline>>=
size_t sorg_getline(char **lineptr, size_t *n, FILE *stream) {
char *bufptr = NULL;
char *p = bufptr;
size_t size;
int c;
if (lineptr == NULL) {
return -1;
}
if (stream == NULL) {
return -1;
}
if (n == NULL) {
return -1;
}
bufptr = *lineptr;
size = *n;
c = fgetc(stream);
if (c == EOF) {
return -1;
}
if (bufptr == NULL) {
bufptr = malloc(128);
if (bufptr == NULL) {
return -1;
}
size = 128;
}
p = bufptr;
while(c != EOF) {
if ((p - bufptr) > (size - 1)) {
size = size + 128;
bufptr = realloc(bufptr, size);
if (bufptr == NULL) {
return -1;
}
}
*p++ = c;
if (c == '\n') {
break;
}
c = fgetc(stream);
}
*lineptr = bufptr;
/* Some text editors do not insert a linebreak on the last line.
* For these cases, shift everything by 1.
*/
if(c == EOF) {
p = p + 1;
size += 1;
}
*p++ = '\0';
*n = size;
return p - bufptr - 1;
}
7.2. Spaces To Underscores
As it turns out, some browsers, such as netsurf, don't work well when references have spaces in them. This function will take in a string and write it to a file handle, replacing the spaces ( ) to underscores (_).
<<function_declarations>>=
static void spaces_to_underscores(const char *str, size_t size, FILE *out);
<<functions>>=
static void spaces_to_underscores(const char *str, size_t size, FILE *out)
{
size_t blksize;
size_t n;
size_t off;
off = 0;
blksize = 0;
for(n = 0; n < size; n++) {
blksize++;
if(str[n] == ' ') {
fwrite(str + off, 1, blksize - 1, out);
fputc('_', out);
blksize = 0;
off = n + 1;
}
}
fwrite(str + off, 1, blksize, out);
}
prev | home | next