Tuesday, January 6, 2009

Erase/Replace

新的一年開始了。

我不要再害怕。

還要活的更從容。

這是這一年的新希望(似乎比往年成熟些?)。唸研究所,不論是知識上或是生活上都真的讓我學到很多很多;假如一直這樣下去,第一個目標也許可以達成一大部分。第二個目標似乎困難許多,但某種程度上也是建立在第一個目標上的吧。

繼續努力。

Sunday, January 4, 2009

Regex for matching floating point numbers

As simple as it sounds, there doesn't seem to be a standard regular expression for matching floating point numbers -- for some reason everyone seems to have their own preference: scientific notation or not, decimal points in the exponent or not... etc. Currently I'm settling with
([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]*\.?[0-9]+)?)

Actually for my purposes, I also need an optional unit, so I'm really using this
([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]*\.?[0-9]+)?)([a-zA-Z]*)

Friday, January 2, 2009

Preventing string truncation with snprintf()

One issue with using snprintf() (the buffer-overrun-preventing version of sprintf()) is that since the size of the char[] we're trying to "print" into is limited, truncation would occur if the string is longer than the char[] size. Yet after studying the manual carefully, I noticed that snprintf() actually returns the length of the resultant string, regardless of the size of the buffer. Below is a simple demonstration of how to prevent truncation with this feature and dynamical allocation of the character buffer.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
#define NC 10
#define ALONGSTRING "A long string of nonsense that would've been truncated."

size_t len;
char *string = calloc(NC, sizeof(*string));

len = snprintf(string, NC, ALONGSTRING);

printf("Truncated string: '%s'\n", string);

if(len >= NC) {
string = realloc(string, (len + 1) * sizeof(*string));
snprintf(string, len + 1, ALONGSTRING);
}

printf("Non-truncated string: '%s'\n", string);

free(string);

return 0;
}