/**
*This program demostrates usage of glib string utility
*This idea is from:http://blog.chinaunix.net/space.php?uid=10540984&do=blog&id=313230
*/
#include
const char* input = "Filesystem Size Used Avail Use% Mounted on\n\
/dev/sda2 9.5G 2.1G 7.0G 23% /\n\
/dev/sda5 1.9G 36M 1.8G 2% /home\n\
/dev/sda3 7.0G 145M 6.5G 3% /test\n\
/dev/sda1 99M 12M 83M 13% /boot\n\
tmpfs 252M 0 252M 0% /dev/shm\n\
/dev/sdb1 380M 117M 244M 33% /backup\n\
/dev/sdb2 618M 17M 570M 3% /ros";
void print_strings(const char* input);
char* remove_duplicated_space(char* input);
int main(int argc,char** argv)
{
print_strings(input);
return 0;
}
/**
*Format input string
*Fields in a line are seperated by only one space character
*/
void print_strings(const char* input)
{
gchar** p = g_strsplit(input,"\n",0);
gchar** lines = p;
//right alignment
for(; *lines != NULL;++lines){
gchar* line = remove_duplicated_space(*lines);
gchar** tmp1 = g_strsplit(line," ",0);
gchar** fields = tmp1;
if(g_strv_length(fields) > 0){
g_printf("%12s\n",fields[0]);
}
g_strfreev(fields);
g_free(line);
}
//left alignment
lines = p;
for(; *lines != NULL;++lines){
gchar* line = remove_duplicated_space(*lines);
gchar** tmp1 = g_strsplit(line," ",0);
gchar** fields = tmp1;
if(g_strv_length(fields) > 0){
g_printf("%-12s\n",fields[0]);
}
g_strfreev(fields);
g_free(line);
}
//you MUST do type-cast explicitly
g_print("%d\n",(gint)2.52);
//Output float
g_print("%f\n",1.7f);
g_print("%3.1f\n",2.52);
g_print("%6.3f\n",2.52);
g_print("%e\n",1.7);
//release input string array
g_strfreev(p);
}
/**
*Remove duplicated spaces
*/
char* remove_duplicated_space(char* input)
{
gchar* p = input;
gchar* d = g_strdup(input);
gchar* p1 = d;
gboolean space = FALSE;
while(p != NULL && *p != 0){
if(*p != ' '){
*(p1++) = *(p++);
space = FALSE;
}
else{
if(!space){
*(p1++) = *(p++);
}
space = TRUE;
p++;
}
}
*p1 = 0;
return d;
}
阅读(4738) | 评论(0) | 转发(0) |