File: Util.c

package info (click to toggle)
spring 104.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 47,512 kB
  • sloc: cpp: 391,093; ansic: 79,943; python: 12,356; java: 12,201; awk: 5,889; sh: 1,826; xml: 655; makefile: 486; perl: 405; php: 211; objc: 194; sed: 2
file content (919 lines) | stat: -rw-r--r-- 21,420 bytes parent folder | download
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
/*
	Copyright (c) 2008 Robin Vobruba <hoijui.quaero@gmail.com>

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>       // fgets()
#include <string.h>      // strcpy(), str...()
#include <stdlib.h>      // malloc(), calloc(), free()
#include <stdarg.h>      // var-args
#include <sys/stat.h>    // used for check if a file exists
#ifdef _WIN32
#include <io.h>          // needed for dir listing
#include <direct.h>      // mkdir()
#else // WIN32
#include <sys/stat.h>    // mkdir()
#include <sys/types.h>   // mkdir()
#include <dirent.h>      // needed for dir listing
#endif // WIN32

#include "Util.h"

#include "System/MainDefines.h"
#include "System/SafeCStrings.h"


char* util_allocStr(unsigned int length) {
	return (char*) calloc(length+1, sizeof(char));
}

char* util_allocStrCpy(const char* toCopy) {

	if (toCopy == NULL) {
		return NULL;
	}

	const size_t copy_sizeMax = strlen(toCopy) + 1;
	char* copy = (char*) calloc(copy_sizeMax, sizeof(char));
	STRCPY_T(copy, copy_sizeMax, toCopy);
	return copy;
}

char* util_allocStrSubCpy(const char* toCopy, int fromPos, int toPos) {

	if (toPos < 0) {
		toPos = strlen(toCopy);
	}

	if (fromPos < 0 || toPos < fromPos) {
		return NULL;
	}

	unsigned int newSize = toPos - fromPos;
	char* copy = (char*) calloc(newSize+1, sizeof(char));
	unsigned int i;
	for (i=0; i < newSize; ++i) {
		copy[i] = toCopy[fromPos + i];
	}

	return copy;
}

char* util_allocStrSubCpyByPointers(const char* toCopy,
		const char* fromPos, const char* toPos) {

	unsigned int newSize = toPos - fromPos;
	char* copy = (char*) calloc(newSize+1, sizeof(char));
	unsigned int i;
	for (i=0; i < newSize; ++i) {
		copy[i] = *(fromPos + i);
	}

	return copy;
}

// ANSI C requires at least one named parameter.
char* util_allocStrCat(int numParts, const char* first, ...) {

	va_list args;
	char *result, *p;
	const char* str;
	size_t length = 0;
	int si;

	// Find the total memory required.
	va_start(args, first);
	for (str = first, si = 0; si < numParts; ++si,
			((str) = (const char *) va_arg(args, const char*))) {
		length += strlen(str);
	}
	va_end(args);

	// Create the string.  Doing the copy ourselves avoids useless string
	// traversals of result, if using strcat(), or string, if using strlen()
	// to increment a pointer into result, at the cost of losing the
	// native optimization of strcat() if any.
	result = util_allocStr(length);
	p = result;
	va_start(args, first);
	for (str = first, si = 0; si < numParts; ++si,
			((str) = (const char *) va_arg(args, const char*))) {
		while (*str != '\0') {
			*p++ = *str++;
		}
	}
	va_end(args);
	*p = '\0';

	return result;
}
// ANSI C requires at least one named parameter.
char* util_allocStrCat_nt(const char* first, ...)
{
	va_list args;
	char *result, *p;
	const char* str;
	size_t length = 0;

	// Find the total memory required.
	va_start(args, first);
	for (str = first; str != NULL;
			((str) = (const char *) va_arg(args, const char*))) {
		length += strlen(str);
	}
	va_end(args);

	// Create the string.  Doing the copy ourselves avoids useless string
	// traversals of result, if using strcat(), or string, if using strlen()
	// to increment a pointer into result, at the cost of losing the
	//native optimization of strcat() if any.
	result = util_allocStr(length);
	p = result;
	va_start(args, first);
	for (str = first; str != NULL;
			((str) = (const char *) va_arg(args, const char*))) {
		while (*str != '\0') {
			*p++ = *str++;
		}
	}
	va_end(args);
	*p = '\0';

	return result;
}
char* util_allocStrCatFSPath(int numParts, const char* first, ...) {

	va_list args;
	char *result, *p;
	const char* str;
	size_t length = 0;
	int si;

	// Find the maximum of the total memory required.
	va_start(args, first);
	for (str = first, si = 0; si < numParts; ++si,
			((str) = (const char *) va_arg(args, const char*))) {
		length += strlen(str);
	}
	va_end(args);
	length += numParts;

	// Create the string.  Doing the copy ourselves avoids useless string
	// traversals of result, if using strcat(), or string, if using strlen()
	// to increment a pointer into result, at the cost of losing the
	// native optimization of strcat() if any.
	result = util_allocStr(length);
	p = result;
	char thisChar;
	char lastChar = '\0';
	va_start(args, first);
	for (str = first, si = 0; si < numParts; ++si,
			((str) = (const char *) va_arg(args, const char*))) {
		if (si > 0 && lastChar != '/') {
			*p++ = '/';
			lastChar = '/';
		}
		while (*str != '\0') {
			thisChar = *str;
			if (thisChar == '\\') {
				thisChar = '/';
			}
			if ((thisChar != '/') || (thisChar != lastChar)) {
				*p = thisChar;
				lastChar = thisChar;
				p++;
			}
			str++;
		}
	}
	va_end(args);
	*p = '\0';
	if (cPS != '/') {
		util_strReplaceChar(result, '/', cPS);
	}

	return result;
}

// 0x20 - space
// 0x09 - horizontal tab
// 0x0a - linefeed
// 0x0b - vertical tab
// 0x0c - form feed
// 0x0d - carriage return
static const char whiteSpaces[] = {0x20, 0x09, 0x0a, 0x0b, 0x0c, 0x0d};
static const int whiteSpaces_size = 6;

bool util_isWhiteSpace(char c) {

	int i;
	for (i=0; i < whiteSpaces_size; ++i) {
		if (c == whiteSpaces[i]) {
			return true;
		}
	}
	return false;
}

void util_strLeftTrim(char* toTrim) {

	if (toTrim == NULL) {
		return;
	}

	int len = strlen(toTrim);
	char* first = toTrim;
	int num = 0;

	// find leading white spaces
	while (*first != '\0') {
		if (util_isWhiteSpace(*first)) {
			first++;
			num++;
			continue;
		}
		break;
	}

	// trim
	if (num > 0) {
		int i;
		// back stack string chars; '\0' inclusive
		for (i=0; i+num <= len; ++i) {
			toTrim[i] = toTrim[i+num];
		}
	}
}
void util_strRightTrim(char* toTrim) {

	if (toTrim == NULL) {
		return;
	}

	int len = strlen(toTrim);
	char* last = toTrim - 1 + len;

	// find trailing white spaces
	while (last > toTrim) {
		if (util_isWhiteSpace(*last)) {
			last--;
			continue;
		}
		break;
	}

	// trim
	*(last+1) = '\0';
}
void util_strTrim(char* toTrim) {

	util_strLeftTrim(toTrim);
	util_strRightTrim(toTrim);
}
char* util_allocStrTrimed(const char* toTrim) {

	char* strCpy = util_allocStrCpy(toTrim);
	util_strTrim(strCpy);
	return strCpy;

}

void util_strReplaceChar(char* toChange, char toFind, char replacer) {

	const unsigned int len = strlen(toChange);
	unsigned int i;
	for (i = 0; i < len; i++) {
		if (toChange[i] == toFind) {
			toChange[i] = replacer;
		}
	}
}
char* util_allocStrReplaceStr(const char* toChange, const char* toFind,
		const char* replacer) {

	// evaluate number of occurences of toFind in toChange
	unsigned int numFinds = 0;
	const char* found = NULL;
	for (found = strstr(toChange, toFind); found != NULL; numFinds++) {
		found = strstr(found+1, toFind);
	}

	int toChange_len = strlen(toChange);
	int toFind_len = strlen(toFind);
	int replacer_len = strlen(replacer);

	// evaluate the result strings length
	unsigned int result_len =
			toChange_len + (numFinds * (replacer_len - toFind_len));
	char* result = util_allocStr(result_len);
	result[0] = '\0';

	const char* endLastFound = toChange;
	for (found = strstr(endLastFound, toFind); found != NULL; ) {
		STRNCAT(result, endLastFound, (found - toChange));
		STRCAT(result, replacer);
		endLastFound = found + toFind_len;
		found = strstr(found+1, toFind);
	}
	STRNCAT(result, endLastFound, (toChange + toChange_len - endLastFound));

	return result;
}

bool util_startsWith(const char* str, const char* prefix) {

	bool startsWith = false;

	const unsigned int l_str = strlen(str);
	const unsigned int l_prefix = strlen(prefix);

	if (l_str >= l_prefix) {
		startsWith = true;

		unsigned int i;
		for (i=0; i < l_prefix; ++i) {
			if (str[i] != prefix[i]) {
				startsWith = false;
				break;
			}
		}
	}

	return startsWith;
}
bool util_endsWith(const char* str, const char* suffix) {

	bool endsWith = false;

	const unsigned int l_str = strlen(str);
	const unsigned int l_suffix = strlen(suffix);

	if (l_str >= l_suffix) {
		endsWith = true;

		unsigned int i;
		for (i = 1; i <= l_suffix; ++i) {
			if (str[l_str - i] != suffix[l_suffix - i]) {
				endsWith = false;
				break;
			}
		}
	}

	return endsWith;
}

bool util_strToBool(const char* str) {

	if (str == NULL) {
		return false;
	}

	bool res = true;

	char* strT = util_allocStrTrimed(str);
	if (strcmp(strT, "0") == 0
			|| strcmp(strT, "NO") == 0
			|| strcmp(strT, "No") == 0
			|| strcmp(strT, "no") == 0
			|| strcmp(strT, "n") == 0
			|| strcmp(strT, "N") == 0
			|| strcmp(strT, "FALSE") == 0
			|| strcmp(strT, "False") == 0
			|| strcmp(strT, "false") == 0
			|| strcmp(strT, "f") == 0
			|| strcmp(strT, "F") == 0)
	{
		res = false;
	}

	free(strT);
	return res;
}


#if defined WIN32
static bool util_isFile(const struct _finddata_t* fileInfo) {
	return !(fileInfo->attrib & _A_SUBDIR)
			&& fileInfo->attrib & (_A_NORMAL | _A_HIDDEN | _A_ARCH);
}
static bool util_isNormalDir(const struct _finddata_t* fileInfo) {
	return strcmp(fileInfo->name, ".") != 0
			&& strcmp(fileInfo->name, "..") != 0
			&& (fileInfo->attrib & _A_SUBDIR);
}
static unsigned int util_listFilesRec(const char* dir, const char* suffix,
		char** fileNames, bool recursive, const unsigned int maxFileNames,
		unsigned int numFileNames, const char* relPath) {

	if (numFileNames >= maxFileNames) {
		return numFileNames;
	}

	struct _finddata_t fileInfo;
	int handle;

	// look for files which end in: suffix
	char* suffixFilesSpec = util_allocStrCat(3, dir, "\\*", suffix);
	handle = _findfirst(suffixFilesSpec, &fileInfo);
	if (handle != -1L) {
		if (util_isFile(&fileInfo)) {
			fileNames[numFileNames++] = util_allocStrCpy(fileInfo.name);
		}
		while (_findnext(handle, &fileInfo) == 0
				&& numFileNames < maxFileNames) {
			if (util_isFile(&fileInfo)) {
				fileNames[numFileNames++] = util_allocStrCat(2, relPath, fileInfo.name);
			}
		}
		_findclose(handle);
	}
	free(suffixFilesSpec);

	// search in sub-directories
	if (recursive) {
		char* subDirsSpec = util_allocStrCat(2, dir, "\\*.*");
		handle = _findfirst(subDirsSpec, &fileInfo);
		if (handle != -1L) {
			// check if not current or parent directories
			if (util_isNormalDir(&fileInfo)) {
				char* subDir = util_allocStrCat(3, dir, "\\", fileInfo.name);
				char* subRelPath = util_allocStrCat(3, relPath, fileInfo.name, "\\");
				numFileNames = util_listFilesRec(subDir, suffix, fileNames,
						recursive, maxFileNames, numFileNames, subRelPath);
				free(subDir);
				free(subRelPath);
			}
			while (_findnext(handle, &fileInfo) == 0
					&& numFileNames < maxFileNames) {
				if (util_isNormalDir(&fileInfo)) {
					char* subDir = util_allocStrCat(3, dir, "\\", fileInfo.name);
					char* subRelPath = util_allocStrCat(3, relPath, fileInfo.name, "\\");
					numFileNames = util_listFilesRec(subDir, suffix, fileNames,
							recursive, maxFileNames, numFileNames, subRelPath);
					free(subDir);
					free(subRelPath);
				}
			}
			_findclose(handle);
		}
		free(subDirsSpec);
	}

	return numFileNames;
}
unsigned int util_listFiles(const char* dir, const char* suffix,
		char** fileNames, bool recursive, const unsigned int maxFileNames) {
	return util_listFilesRec(
			dir, suffix, fileNames, recursive, maxFileNames, 0, "");
}
#else // defined WIN32

static const char* fileSelectorSuffix = NULL;

static void util_initFileSelector(const char* suffix) {
	fileSelectorSuffix = suffix;
}

#if defined(__APPLE__)
static int util_fileSelector(struct dirent* fileDesc) {
#else
static int util_fileSelector(const struct dirent* fileDesc) {
#endif
	return util_endsWith(fileDesc->d_name, fileSelectorSuffix);
}

static unsigned int util_listFilesU(const char* dir, struct dirent*** files) {

	int foundDirs = scandir(dir, files, &util_fileSelector, alphasort);

	if (foundDirs < 0) { // error, act as if no file found
		foundDirs = 0;
	}

	return (unsigned int) foundDirs;
}

static unsigned int util_listFilesRec(const char* dir, const char* suffix,
		char** fileNames, bool recursive, const unsigned int maxFileNames,
		unsigned int numFiles, const char* relPath) {

	struct dirent** files;
	util_initFileSelector(suffix);
	unsigned int currentNumFiles = util_listFilesU(dir, &files);
	unsigned int f;
	for (f = 0; f < currentNumFiles && numFiles < maxFileNames; ++f) {
		fileNames[numFiles++] = util_allocStrCat(2, relPath, files[f]->d_name);
	}
/*
	for (; f < currentNumFiles; ++f) {
		free(files[f]);
	}
*/

	if (recursive) {
		struct stat dirStat;
		util_initFileSelector("");
		currentNumFiles = util_listFilesU(dir, &files);
		for (f = 0; f < currentNumFiles && numFiles < maxFileNames; ++f) {
			if (strcmp(files[f]->d_name, ".") == 0
					|| strcmp(files[f]->d_name, "..") == 0) {
				continue;
			}
			char* subDir = util_allocStrCat(4, dir, "/", relPath, files[f]->d_name);
			char* subRelPath = util_allocStrCat(3, relPath, files[f]->d_name, "/");
			int retStat = stat(subDir, &dirStat);
			if (retStat == 0 && S_ISDIR(dirStat.st_mode)) {
				numFiles = util_listFilesRec(subDir, suffix, fileNames,
						recursive, maxFileNames, numFiles, subRelPath);
			}
			free(subDir);
			free(subRelPath);
		}
	}

	return numFiles;
}
unsigned int util_listFiles(const char* dir, const char* suffix,
		char** fileNames, bool recursive, const unsigned int maxFileNames) {
	return util_listFilesRec(
			dir, suffix, fileNames, recursive, maxFileNames, 0, "");
}
#endif // defined WIN32

void util_removeTrailingSlash(char* fsPath) {

	if (fsPath != NULL && strlen(fsPath)) {
		int len = strlen(fsPath);
		if (len > 0) {
			char lastChar = fsPath[len-1];
			if ((lastChar == '/') || (lastChar == '\\')) {
				fsPath[len-1] = '\0';
			}
		}
	}
}

bool util_fileExists(const char* filePath) {

	struct stat fileInfo;
	bool exists;
	int intStat;

	char* filePath_cpy = util_allocStrCpy(filePath);
	util_removeTrailingSlash(filePath_cpy);

	// Attempt to get the file attributes
	intStat = stat(filePath_cpy, &fileInfo);
	if (intStat == 0) {
		// We were able to get the file attributes
		// so the file obviously exists.
		exists = true;
	} else {
		// We were not able to get the file attributes.
		// This may mean that we don't have permission to
		// access the folder which contains this file. If you
		// need to do that level of checking, lookup the
		// return values of stat which will give you
		// more details on why stat failed.
		exists = false;
	}
	free(filePath_cpy);

	return exists;
}

static bool util_makeDirS(const char* dirPath) {

	#if defined WIN32
		int mkStat = _mkdir(dirPath);
		if (mkStat == 0) {
			return true;
		} else {
			return false;
		}
	#else // defined WIN32
		// with read/write/search permissions for owner and group,
		// and with read/search permissions for others
		int mkStat = mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
		if (mkStat == 0) {
			return true;
		} else {
			return false;
		}
	#endif // defined WIN32
}

bool util_makeDir(const char* dirPath, bool recursive) {

	char* dirPath_cpy = util_allocStrCpy(dirPath);
	util_removeTrailingSlash(dirPath_cpy);

	bool exists = util_fileExists(dirPath_cpy);

	if (!exists) {
		char* parentDir = util_allocStrCpy(dirPath_cpy);
		bool evaluatedParent = util_getParentDir(parentDir);
		if (evaluatedParent) {
			bool parentExists = util_fileExists(parentDir);

			if (!parentExists && recursive) {
				parentExists = util_makeDir(parentDir, recursive);
			}

			if (parentExists) {
				exists = util_makeDirS(dirPath_cpy);
			}
		}
		free(parentDir);
		parentDir = NULL;
	}
	free(dirPath_cpy);

	return exists;
}

bool util_getParentDir(char* path) {
	if (path == NULL)
		return false;
	util_removeTrailingSlash(path);

	char* ptr = strrchr(path, '/'); // search char from end reverse
	if (ptr == NULL) {
		ptr = strrchr(path, '\\'); // search char from end reverse
		if (ptr == NULL) {
			return false;
		}
	}

	// replace the last '/' or '\\' with an string terminationg char
	*ptr = '\0';

	return true;
}

bool util_isPathAbsolute(const char* path) {

	if (path == NULL) {
		return false;
	}

#ifdef _WIN32
	return strlen(path) > 2 && path[1] == ':' && (path[2] == '\\' || path[2] == '/');
#else // _WIN32
	return strlen(path) > 0 && path[0] == '/';
#endif // _WIN32
}

bool util_findFile(const char* dirs[], unsigned int numDirs,
		const char* relativeFilePath, char* absoluteFilePath,
		bool searchOnlyWriteable) {

	bool found = false;

	if (util_isPathAbsolute(relativeFilePath)) {
		STRCPY(absoluteFilePath, relativeFilePath);
		found = true;
	}

	if (!found && searchOnlyWriteable && numDirs > 1) {
		numDirs = 1;
	}

	unsigned int d;
	for (d=0; d < numDirs && !found; ++d) {
		char* tmpPath = util_allocStrCatFSPath(2, dirs[d], relativeFilePath);

		if (util_fileExists(tmpPath)) {
			STRCPY(absoluteFilePath, tmpPath);
			found = true;
		}

		free(tmpPath);
		tmpPath = NULL;
	}

	return found;
}

bool util_findDir(const char* dirs[], unsigned int numDirs,
		const char* relativeDirPath, char* absoluteDirPath,
		bool searchOnlyWriteable, bool create) {

	bool found = false;

	// check if it is an absolute file path
	if (util_fileExists(relativeDirPath)) {
		STRCPY(absoluteDirPath, relativeDirPath);
		found = true;
	}

	if (searchOnlyWriteable && numDirs > 1) {
		numDirs = 1;
	}

	unsigned int d;
	for (d=0; d < numDirs && !found; ++d) {
		char* tmpPath = util_allocStrCatFSPath(2, dirs[d], relativeDirPath);

		if (util_fileExists(tmpPath)) {
			STRCPY(absoluteDirPath, tmpPath);
			found = true;
		}

		free(tmpPath);
		tmpPath = NULL;
	}

	// not found -> create it
	if (!found && create && numDirs >= 1) {
		// use dirs[0], as it is assumed this is the writable dir
		char* tmpPath = util_allocStrCatFSPath(2, dirs[0], relativeDirPath);
		STRCPY(absoluteDirPath, tmpPath);
		free(tmpPath);
		tmpPath = NULL;
		found = util_makeDir(absoluteDirPath, true);
	}

	return found;
}

static inline bool util_isEndOfLine(char c) {
	return (c == '\r') || (c == '\n');
}
/**
 * Saves the property found in propLine into the arrays at the given index.
 * @return  false if no property was found at this line
 */
static bool util_parseProperty(const char* propLine,
		const char* keys[], const char* values[], int propStoreIndex) {

	const unsigned int len = strlen(propLine);
	unsigned int pos = 0; // current pos
	char c; // current char

	// skip white spaces
	while (pos < len) {
		c = propLine[pos];
		if (util_isWhiteSpace(c)) {
			pos++;
		} else {
			break;
		}
	}

	// return, if the line was empty (contained only white spaces)
	if (pos >= len) {
		return false;
	}

	// check if it is a comment line
	if (pos < len) {
		c = propLine[pos];
		if ((c == '#') || (c == ';')) {
			return false;
		}
	}

	// now it has to be a property line
	// if not: bad properties file format

	// read the key
	int keyStartPos = pos;
	char* key = NULL;
	while (pos < len) {
		c = propLine[pos];
		bool wb = util_isWhiteSpace(c);
		bool es = (c == '=');
		if (!wb && !es) {
			pos++;
		} else {
			break;
		}
	}
	key = util_allocStrSubCpy(propLine, keyStartPos, pos);

	// skip white spaces
	while (pos < len) {
		c = propLine[pos];
		if (util_isWhiteSpace(c)) {
			pos++;
		} else {
			break;
		}
	}

	// check if it is an equals sign: '='
	if (pos < len) {
		c = propLine[pos];
		if (c != '=') {
			free(key);
			key = NULL;
			return false;
		}
		pos++;
	} else {
		free(key);
		key = NULL;
		return false;
	}

	// skip white spaces
	while (pos < len) {
		c = propLine[pos];
		if (util_isWhiteSpace(c)) {
			pos++;
		} else {
			break;
		}
	}

	// read the value
	int valueStartPos = pos;
	char* value = NULL;
	while (pos < len) {
		c = propLine[pos];
		bool eol = util_isEndOfLine(c);
		if (!eol) {
			pos++;
		} else {
			break;
		}
	}
	value = util_allocStrSubCpy(propLine, valueStartPos, pos);

	keys[propStoreIndex] = key;
	values[propStoreIndex] = value;

	return true;
}

#define MAXLINELENGTH 2048
int util_parsePropertiesFile(const char* propertiesFile,
		const char* keys[], const char* values[], int maxProperties) {

	int numProperties = 0;

	FILE* file;
	char line[MAXLINELENGTH + 1];

	file = fopen(propertiesFile , "r");
	if (file == NULL) {
		return numProperties;
	}

	char* error = NULL;
	bool propertyFound = false;
	while (numProperties < maxProperties) {
		// returns NULL on error or EOF
		error = fgets(line, MAXLINELENGTH + 1, file);
		if (error == NULL) {
			break;
		}
		// remove EOL chars
		int lci = strlen(line)-1;
		while (lci >= 0 && util_isEndOfLine(line[lci])) {
			line[lci] = '\0';
			lci--;
		}
		propertyFound = util_parseProperty(line, keys, values, numProperties);
		if (propertyFound) {
			numProperties++;
		}
	}
	fclose(file);

	return numProperties;
}

const char* util_map_getValueByKey(
		unsigned int mapSize,
		const char** mapKeys, const char** mapValues,
		const char* key) {

	const char* value = NULL;

	unsigned int i;
	for (i = 0; i < mapSize; i++) {
		if (strcmp(mapKeys[i], key) == 0) {
			value = mapValues[i];
			break;
		}
	}

	return value;
}

void util_finalize() {}