1 |
/* $Id: utils_misc.c,v 1.3 2006/06/16 19:39:07 joko Exp $ */ |
2 |
|
3 |
#include <stdio.h> |
4 |
#include <windows.h> |
5 |
|
6 |
// if last char is newline, "strip" it |
7 |
void chomp(char * string) { |
8 |
int string_length = strlen(string); |
9 |
if (string[string_length-1] == '\n') { |
10 |
string[string_length-1] = '\0'; |
11 |
} |
12 |
} |
13 |
|
14 |
// strip leading and trailing whitespace |
15 |
void trim(char ** string) { |
16 |
|
17 |
// string length and loop variable |
18 |
int string_length, i; |
19 |
|
20 |
// contains current character at string position i |
21 |
char current_char[2]; |
22 |
|
23 |
// pointers to begin end tail of new (stripped) string |
24 |
char * begin; |
25 |
char * tail; |
26 |
|
27 |
// prepare to be used with "strcmp" (comparison string should be terminated properly) |
28 |
current_char[1] = '\0'; |
29 |
|
30 |
|
31 |
/***************************** |
32 |
* 1. strip leading spaces |
33 |
**/ |
34 |
begin = *string; |
35 |
string_length = strlen(*string); |
36 |
|
37 |
// loop through all string characters (from left to right) |
38 |
for (i = 0; i < string_length; i++) { |
39 |
|
40 |
// get character at position i |
41 |
current_char[0] = *(*string + i); |
42 |
|
43 |
// is it a space? then increase pointer to begin of "new" string |
44 |
if (strcmp(current_char, " ") == 0) { |
45 |
begin++; |
46 |
} else { |
47 |
break; |
48 |
} |
49 |
} |
50 |
*string = begin; |
51 |
|
52 |
|
53 |
/***************************** |
54 |
* 2. strip trailing spaces |
55 |
**/ |
56 |
|
57 |
// calculate new string length |
58 |
string_length = strlen(*string); |
59 |
|
60 |
// loop through all string characters (from right to left) |
61 |
for (i = 0; i < string_length - 1; i++) { |
62 |
|
63 |
// get character at position string_length - i |
64 |
tail = *string + string_length - 1 - i; |
65 |
current_char[0] = *tail; |
66 |
|
67 |
// is it a space? then set null-byte to indicate end of "new" string at current position |
68 |
if (strcmp(current_char, " ") == 0) { |
69 |
*tail = '\0'; |
70 |
} else { |
71 |
break; |
72 |
} |
73 |
} |
74 |
|
75 |
} |
76 |
|
77 |
|
78 |
// checks for error and writes its message to stderr |
79 |
BOOL check_alert_error(const char * error_source) { |
80 |
DWORD dwError = GetLastError(); |
81 |
|
82 |
HLOCAL message = NULL; |
83 |
BOOL fOk; |
84 |
|
85 |
if (dwError == 0) |
86 |
return FALSE; |
87 |
|
88 |
fOk = FormatMessage( |
89 |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, |
90 |
NULL, |
91 |
dwError, |
92 |
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), |
93 |
(PTSTR)&message, |
94 |
0, |
95 |
NULL |
96 |
); |
97 |
|
98 |
if (message != NULL) { |
99 |
fprintf(stderr, "ERROR with '%s': %s (Code %i)\n", error_source, message, dwError); |
100 |
LocalFree(message); |
101 |
} |
102 |
|
103 |
return TRUE; |
104 |
|
105 |
} |