-
Notifications
You must be signed in to change notification settings - Fork 2
/
OSMisc.h
2081 lines (1753 loc) · 51.8 KB
/
OSMisc.h
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************************************************:')
OSMisc.h
Miscellaneous things.
Fabrice Le Bars
Created : 2009-01-28
***************************************************************************************************************:)*/
// Prevent Visual Studio Intellisense from defining _WIN32 and _MSC_VER when we use
// Visual Studio to edit Linux or Borland C++ code.
#ifdef __linux__
# undef _WIN32
#endif // __linux__
#if defined(__GNUC__) || defined(__BORLANDC__)
# undef _MSC_VER
#endif // defined(__GNUC__) || defined(__BORLANDC__)
#ifndef OSMISC_H
#define OSMISC_H
#ifdef WINCE
#define DISABLE_USER_INPUT_FUNCTIONS
#define DISABLE_USER_INPUT_TIMEOUT_FUNCTIONS
#endif // WINCE
#include "OSCore.h"
#ifndef DISABLE_USER_INPUT_FUNCTIONS
#ifndef DISABLE_USER_INPUT_TIMEOUT_FUNCTIONS
#include "OSTime.h"
#endif // !DISABLE_USER_INPUT_TIMEOUT_FUNCTIONS
#endif // !DISABLE_USER_INPUT_FUNCTIONS
/*
Debug macros specific to OSMisc.
*/
#ifdef _DEBUG_MESSAGES_OSUTILS
# define _DEBUG_MESSAGES_OSMISC
#endif // _DEBUG_MESSAGES_OSUTILS
#ifdef _DEBUG_WARNINGS_OSUTILS
# define _DEBUG_WARNINGS_OSMISC
#endif // _DEBUG_WARNINGS_OSUTILS
#ifdef _DEBUG_ERRORS_OSUTILS
# define _DEBUG_ERRORS_OSMISC
#endif // _DEBUG_ERRORS_OSUTILS
#ifdef _DEBUG_MESSAGES_OSMISC
# define PRINT_DEBUG_MESSAGE_OSMISC(params) PRINT_DEBUG_MESSAGE(params)
#else
# define PRINT_DEBUG_MESSAGE_OSMISC(params)
#endif // _DEBUG_MESSAGES_OSMISC
#ifdef _DEBUG_WARNINGS_OSMISC
# define PRINT_DEBUG_WARNING_OSMISC(params) PRINT_DEBUG_WARNING(params)
#else
# define PRINT_DEBUG_WARNING_OSMISC(params)
#endif // _DEBUG_WARNINGS_OSMISC
#ifdef _DEBUG_ERRORS_OSMISC
# define PRINT_DEBUG_ERROR_OSMISC(params) PRINT_DEBUG_ERROR(params)
#else
# define PRINT_DEBUG_ERROR_OSMISC(params)
#endif // _DEBUG_ERRORS_OSMISC
#ifndef DISABLE_USER_INPUT_FUNCTIONS
#ifdef _WIN32
#else
#ifndef DISABLE_CUSTOM_BAUDRATE
#ifdef __linux__
#pragma push_macro("termios")
#undef termios
#define termios termbits_termios
#include <asm/termbits.h> // Not compatible with termios.h, see https://stackoverflow.com/questions/37710525/including-termios-h-and-asm-termios-h-in-the-same-project...
#undef termios
#pragma pop_macro("termios")
#endif // __linux__
#endif // !DISABLE_CUSTOM_BAUDRATE
#include <termios.h>
#endif // _WIN32
#endif // !DISABLE_USER_INPUT_FUNCTIONS
#ifndef DISABLE_REBOOT_FUNCTIONS
#ifdef _WIN32
#else
#include <sys/reboot.h>
#endif // _WIN32
#endif // !DISABLE_REBOOT_FUNCTIONS
//// To check...
//#ifdef __GNUC__
//#define _stricmp strcasecmp
//#define _strnicmp strncasecmp
//#define stricmp _stricmp
//#define strnicmp _strnicmp
//#endif // __GNUC__
// Need to be undefined at the end of the file...
// min and max might cause incompatibilities...
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif // !max
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif // !min
#define MAX_BUF_LEN 256
#define MAX_TIMEOUT_PROMPTGETUSERINPUTTIMEOUT 25500
// Kelvin to Celsius degrees conversions.
#define KELVIN2CELSIUS(temperature) ((temperature)-273.15)
#define CELSIUS2KELVIN(temperature) ((temperature)+273.15)
#define STANDARD_GRAVITY 9.80665
// Earth radius in m.
#define EARTH_RADIUS 6371000
#define EAST_NORTH_UP_COORDINATE_SYSTEM 0
#define NORTH_EAST_DOWN_COORDINATE_SYSTEM 1
#define NORTH_WEST_UP_COORDINATE_SYSTEM 2
#ifndef SQR_DEFINED
#define SQR_DEFINED
#ifndef sqr
/*
Compute the square of a value.
double x : (IN) Value.
Return : The square of x.
*/
inline double sqr(double x)
{
return x*x;
}
#endif // !sqr
#endif // !SQR_DEFINED
#ifndef sq
#define sq(x) ((x)*(x))
#endif // !sq
#ifndef SIGN_DEFINED
#define SIGN_DEFINED
#ifndef sign
/*
Return +1 if x is positive, -1 if x is negative or x/epsilon if x is between -epsilon and epsilon.
double x : (IN) Value.
double epsilon : (IN) Threshold.
Return : +1, -1 or x/epsilon.
*/
inline double sign(double x, double epsilon)
{
if (x >= epsilon)
return 1;
else if (x <= -epsilon)
return -1;
else if (epsilon == 0)
return 0;
else
return x/epsilon;
}
#endif // !sign
#endif // !SIGN_DEFINED
#ifndef HYSTERESIS_DEFINED
#define HYSTERESIS_DEFINED
//#ifndef hysteresis
/*
Hysteresis.
double in : (IN) Input value.
double out : (IN) Current output value, should be -1 or 1.
double epsilon : (IN) Current output value should be kept if input value is in
[-epsilon;epsilon[.
Return : +1, -1 or out.
*/
inline double hysteresis(double in, double out, double epsilon)
{
if (in >= epsilon) out = 1;
else if (in < -epsilon) out = -1;
return out;
}
//#endif // !hysteresis
#endif // !HYSTERESIS_DEFINED
#ifndef constrain
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#endif // !constrain
// See https://www.arduino.cc/reference/en/language/functions/math/map/.
inline double remap2range(double x, double in_min, double in_max, double out_min, double out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
inline double quantification(double v, double step)
{
//double q = 0;
//q = q >= 0? floor(v/step+0.5): ceil(v/step-0.5);
//q = q*step;
return floor(v/step+0.5)*step;
}
// In rad.
inline void quaternion2euler(double qw, double qx, double qy, double qz, double* pRoll, double* pPitch, double* pYaw)
{
*pRoll = atan2(2*qy*qz+2*qw*qx, 2*sqr(qw)+2*sqr(qz)-1);
*pPitch = -asin(constrain(2*qx*qz-2*qw*qy, -1, 1)); // Attempt to avoid potential NAN...
*pYaw = atan2(2*qx*qy+2*qw*qz, 2*sqr(qw)+2*sqr(qx)-1);
}
// In rad.
inline void euler2quaternion(double roll, double pitch, double yaw, double* pQw, double* pQx, double* pQy, double* pQz)
{
double t0 = cos(yaw * 0.5);
double t1 = sin(yaw * 0.5);
double t2 = cos(roll * 0.5);
double t3 = sin(roll * 0.5);
double t4 = cos(pitch * 0.5);
double t5 = sin(pitch * 0.5);
*pQw = t0 * t2 * t4 + t1 * t3 * t5;
*pQx = t0 * t3 * t4 - t1 * t2 * t5;
*pQy = t0 * t2 * t5 + t1 * t3 * t4;
*pQz = t1 * t2 * t4 - t0 * t3 * t5;
}
/*
Get the depth from the pressure (pressure difference = density x g x height).
double pressure : (IN) Pressure in bar.
double pressureref : (IN) Pressure at the surface in bar, used as reference (e.g. 1).
double density : (IN) Water density in kg/m3 (e.g. 1000).
Return : The depth in m.
*/
inline double Pressure2Height(double pressure, double pressureref, double density)
{
return -(pressure-pressureref)*1e5/(density*STANDARD_GRAVITY);
}
/*
Get the pressure from the depth (pressure difference = density x g x height).
double depth : (IN) Depth in m.
double pressureref : (IN) Pressure at the surface in bar, used as reference (e.g. 1).
double density : (IN) Water density in kg/m3 (e.g. 1000).
Return : The pressure in bar.
*/
inline double Height2Pressure(double height, double pressureref, double density)
{
return -(density*STANDARD_GRAVITY)*height/1e5+pressureref;
}
/*
Return an angle between 0 and 2*M_PI.
double theta : (IN) Value.
Return : The converted angle.
*/
inline double fmod_2PI_pos(double theta)
{
return fmod(fmod(theta, 2*M_PI)+2*M_PI, 2*M_PI);
}
/*
Return an angle between -M_PI and M_PI.
double theta : (IN) Value.
Return : The converted angle.
*/
inline double fmod_2PI(double theta)
{
return fmod(fmod(theta, 2*M_PI)+3*M_PI, 2*M_PI)-M_PI;
}
/*
Return an angle between 0 and 360.
double theta : (IN) Value.
Return : The converted angle.
*/
inline double fmod_360_pos(double theta)
{
return fmod(fmod(theta, 2*180.0)+2*180.0, 2*180.0);
}
/*
Return an angle between -180 and 180.
double theta : (IN) Value.
Return : The converted angle.
*/
inline double fmod_360(double theta)
{
return fmod(fmod(theta, 2*180.0)+3*180.0, 2*180.0)-180.0;
}
/*
Convert any angle in rad to an angle between 0 and 360 deg.
double theta : (IN) Value in rad.
Return : The converted angle in deg.
*/
inline double fmod_360_pos_rad2deg(double theta)
{
return fmod(fmod(theta*180.0/M_PI, 2*180.0)+2*180.0, 2*180.0);
}
/*
Convert any angle in rad to an angle between -180 and 180 deg.
double theta : (IN) Value in rad.
Return : The converted angle in deg.
*/
inline double fmod_360_rad2deg(double theta)
{
return fmod(fmod(theta*180.0/M_PI, 2*180.0)+3*180.0, 2*180.0)-180.0;
}
/*
Convert any angle in deg to an angle between 0 and 2*M_PI rad.
double theta : (IN) Value in deg.
Return : The converted angle in rad.
*/
inline double fmod_2PI_pos_deg2rad(double theta)
{
return fmod(fmod(theta*M_PI/180.0, 2*M_PI)+2*M_PI, 2*M_PI);
}
/*
Convert any angle in deg to an angle between -M_PI and M_PI rad.
double theta : (IN) Value in deg.
Return : The converted angle in rad.
*/
inline double fmod_2PI_deg2rad(double theta)
{
return fmod(fmod(theta*M_PI/180.0, 2*M_PI)+3*M_PI, 2*M_PI)-M_PI;
}
#ifndef MEAN_DEFINED
#define MEAN_DEFINED
#ifndef mean
/*
Compute the mean of a table.
double* tab : (IN) Table.
int tab_length : (IN) Number of elements in the table.
Return : The mean.
*/
inline double mean(double* tab, int tab_length)
{
double m = 0;
int i = 0;
for (i = tab_length-1; i >= 0; i--)
{
m += tab[i];
}
m = m/tab_length;
return m;
}
#endif // !mean
#endif // !MEAN_DEFINED
#ifndef VAR_DEFINED
#define VAR_DEFINED
#ifndef var
/*
Compute the variance of a table.
double* tab : (IN) Table.
int tab_length : (IN) Number of elements in the table.
Return : The variance.
*/
inline double var(double* tab, int tab_length)
{
double m = 0;
double v = 0;
int i = 0;
for (i = tab_length-1; i >= 0; i--)
{
m += tab[i];
}
m = m/tab_length;
for (i = tab_length-1; i >= 0; i--)
{
v += sqr(tab[i]-m);
}
v = v/tab_length;
return v;
}
#endif // !var
#endif // !VAR_DEFINED
/*
Compute the mean of a table using a table of numbers of occurences for each value.
double* tab_values : (IN) Table of the different values.
double* tab_numbers : (IN) Table of the number of occurences for each value.
int tab_length : (IN) Number of elements in the table of values (should be the same for
the table of numbers).
Return : The mean.
*/
inline double meann(double* tab_values, double* tab_numbers, int tab_length)
{
double m = 0;
double n = 0;
int i = 0;
for (i = tab_length-1; i >= 0; i--)
{
n += tab_numbers[i];
m += tab_numbers[i]*tab_values[i];
}
m = m/n;
return m;
}
/*
Compute the variance of a table using a table of numbers of occurences for each value.
double* tab_values : (IN) Table of the different values.
double* tab_numbers : (IN) Table of the number of occurences for each value.
int tab_length : (IN) Number of elements in the table of values (should be the same for
the table of numbers).
Return : The variance.
*/
inline double varn(double* tab_values, double* tab_numbers, int tab_length)
{
double m = 0;
double v = 0;
double n = 0;
int i = 0;
for (i = tab_length-1; i >= 0; i--)
{
n += tab_numbers[i];
m += tab_numbers[i]*tab_values[i];
}
m = m/n;
for (i = tab_length-1; i >= 0; i--)
{
v += tab_numbers[i]*sqr(tab_values[i]-m);
}
v = v/n;
return v;
}
// https://en.wikiversity.org/wiki/C_Source_Code/Find_the_median_and_mean
// https://www.tutorialspoint.com/learn_c_by_examples/median_program_in_c.htm
inline double median(double* tab_values, int tab_length)
{
double temp = 0;
int i = 0, j = 0;
int n = tab_length;
double* x = tab_values;
// The following two loops sort the array x in ascending order.
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (x[j] < x[i]) {
// Swap elements.
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
return x[n/2];
}
// https://en.wikiversity.org/wiki/C_Source_Code/Find_the_median_and_mean
// https://www.tutorialspoint.com/learn_c_by_examples/median_program_in_c.htm
inline double median2(double* tab_values, int tab_length)
{
double temp = 0;
int i = 0, j = 0;
int n = tab_length;
double* x = tab_values;
// The following two loops sort the array x in ascending order.
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (x[j] < x[i]) {
// Swap elements.
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
if (n%2 == 0)
{
// For an even number of elements, return the mean of the two elements in the middle.
return ((x[n/2]+x[n/2-1])/2.0);
}
else
{
// Return the element in the middle.
return x[n/2];
}
}
// https://fr.wikipedia.org/wiki/Moyenne_mobile
// https://en.wikipedia.org/wiki/Moving_average
// http://www.cafemath.fr/mathblog/article.php?page=MovingAverages.php
inline double rect_mv_avg(double newvalue, double oldestvalue, double prevaverage, int n)
{
return prevaverage+(newvalue-oldestvalue)/(double)n;
}
inline double exp_mv_avg(double newvalue, double prevaverage, double alpha)
{
return alpha*prevaverage+(1.0-alpha)*newvalue;
}
// See also https://gist.github.com/mrfaptastic/3fd6394c5d6294c993d8b42b026578da?
#ifndef FGETS2_DEFINED
#define FGETS2_DEFINED
/*
Return a line of a file using fgets(), skipping lines that begin with a '%'.
Return NULL when a line begins with a '$' or when fgets() returns NULL.
FILE* file : (IN) Pointer to a file.
char* line : (IN) Storage location for data.
int nbChar : (IN) Maximum number of characters to read.
Return : The line or NULL.
*/
inline char* fgets2(FILE* file, char* line, int nbChar)
{
char* r = NULL;
do
{
r = fgets(line, nbChar, file);
}
while ((line[0] == '%') && (r != NULL));
if (line[0] == '$')
{
r = NULL;
}
return r;
}
#endif // !FGETS2_DEFINED
/*
Return a line of a file using fgets(), skipping lines that begin with a '%'
(Scilab-style comments), a '#' (Linux configuration files-style comments) or
"//" (C-style comments).
Return NULL when a line begins with a '$' or when fgets() returns NULL, or if
the maximum number of characters to read is less than 2.
FILE* file : (IN) Pointer to a file.
char* line : (IN) Storage location for data.
int nbChar : (IN) Maximum number of characters to read.
Return : The line or NULL.
*/
inline char* fgets3(FILE* file, char* line, int nbChar)
{
char* r = NULL;
if (nbChar < 2)
{
return NULL;
}
do
{
r = fgets(line, nbChar, file);
}
while ((
(line[0] == '%')||
(line[0] == '#')||
((line[0] == '/')&&(line[1] == '/'))
) && (r != NULL));
if (line[0] == '$')
{
r = NULL;
}
return r;
}
/*
Return a line of a file using fgets(), skipping lines that begin with a '%'
(Scilab-style comments), a '#' (Linux configuration files-style comments) or
"//" (C-style comments).
Return NULL when fgets() returns NULL, or if
the maximum number of characters to read is less than 2.
FILE* file : (IN) Pointer to a file.
char* line : (IN) Storage location for data.
int nbChar : (IN) Maximum number of characters to read.
Return : The line or NULL.
*/
inline char* fgets4(FILE* file, char* line, int nbChar)
{
char* r = NULL;
if (nbChar < 2)
{
return NULL;
}
do
{
r = fgets(line, nbChar, file);
}
while ((
(line[0] == '%')||
(line[0] == '#')||
((line[0] == '/')&&(line[1] == '/'))
) && (r != NULL));
return r;
}
/*
Return a line from an input file using fgets(), skipping lines that begin with a '%'
(Scilab-style comments), a '#' (Linux configuration files-style comments) or
"//" (C-style comments).
Return NULL when a line begins with a '$' or when fgets() returns NULL, or if
the maximum number of characters to read is less than 2.
All the skipped lines are saved to the output file.
FILE* filein : (IN) Pointer to an input file.
FILE* fileout : (IN) Pointer to an output file.
char* line : (IN) Storage location for data.
int nbChar : (IN) Maximum number of characters to read.
Return : The line or NULL.
*/
inline char* fgetscopy3(FILE* filein, FILE* fileout, char* line, int nbChar)
{
char* r = NULL;
if (nbChar < 2)
{
return NULL;
}
for (;;)
{
r = fgets(line, nbChar, filein);
if ((
(line[0] == '%')||
(line[0] == '#')||
((line[0] == '/')&&(line[1] == '/'))
) && (r != NULL))
{
if (fprintf(fileout, "%s", line) < 0) return NULL;
}
else
{
break;
}
}
if (line[0] == '$')
{
if (r != NULL) fprintf(fileout, "%s", line);
r = NULL;
}
return r;
}
/*
Return : The current line number or -1 if an error occurs.
*/
inline int ftellline(FILE* file)
{
int cur = 0, i = 0;
char* r = NULL;
char line[1024];
cur = ftell(file);
rewind(file);
do
{
do
{
r = fgets(line, sizeof(line), file);
if (r == NULL)
{
// Go back to initial position.
fseek(file, cur, SEEK_SET);
return -1;
}
} while ((strlen(r) == sizeof(line)-1)&&(r[sizeof(line)-2] != '\n'));
i++;
} while (ftell(file) <= cur);
// Go back to initial position.
if (fseek(file, cur, SEEK_SET) != EXIT_SUCCESS) return -1;
return i;
}
/*
Return : EXIT_SUCCESS or EXIT_FAILURE if linenumber does not exist and in this case
the file tries to stay at its original position unless a file error occurs.
*/
inline int fsetline(FILE* file, int linenumber)
{
int cur = 0, i = 0;
char* r = NULL;
char line[1024];
if (linenumber <= 0) return EXIT_FAILURE;
cur = ftell(file);
rewind(file);
while (i < linenumber-1)
{
do
{
r = fgets(line, sizeof(line), file);
if (r == NULL)
{
// If fgets() fails, try to go back to initial position.
clearerr(file);
fseek(file, cur, SEEK_SET);
return EXIT_FAILURE;
}
} while ((strlen(r) == sizeof(line)-1)&&(r[sizeof(line)-2] != '\n'));
i++;
}
return EXIT_SUCCESS;
}
inline int fload(char* szFilePath, unsigned char* buf, size_t elementsize, size_t count, size_t* pBytesLoaded)
{
FILE* file = NULL;
file = fopen(szFilePath, "rb");
if (file == NULL)
{
return EXIT_FAILURE;
}
*pBytesLoaded = fread(buf, elementsize, count, file);
if (*pBytesLoaded <= 0)
{
// Empty file, elementsize or count is 0, or there was an error.
fclose(file);
return EXIT_FAILURE;
}
if (feof(file) == 0)
{
// buf was not big enough or there was an error.
fclose(file);
return EXIT_FAILURE;
}
if (fclose(file) != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
inline int fsave(char* szFilePath, unsigned char* buf, size_t elementsize, size_t count, size_t* pBytesSaved)
{
FILE* file = NULL;
file = fopen(szFilePath, "wb");
if (file == NULL)
{
return EXIT_FAILURE;
}
*pBytesSaved = fwrite(buf, elementsize, count, file);
if (*pBytesSaved != elementsize*count)
{
fclose(file);
return EXIT_FAILURE;
}
if (fclose(file) != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
inline int fcopyload(char* szFromFilePath, char* szToFilePath, unsigned char* buf, size_t elementsize, size_t count, size_t* pBytesCopied)
{
FILE* fromfile = NULL;
FILE* tofile = NULL;
size_t BytesRead = 0;
fromfile = fopen(szFromFilePath, "rb");
if (fromfile == NULL)
{
return EXIT_FAILURE;
}
tofile = fopen(szToFilePath, "wb");
if (tofile == NULL)
{
fclose(fromfile);
return EXIT_FAILURE;
}
BytesRead = fread(buf, elementsize, count, fromfile);
if (BytesRead <= 0)
{
// Empty file, elementsize or count is 0, or there was an error.
fclose(tofile);
fclose(fromfile);
return EXIT_FAILURE;
}
if (feof(fromfile) == 0)
{
// buf was not big enough or there was an error.
fclose(tofile);
fclose(fromfile);
return EXIT_FAILURE;
}
*pBytesCopied = fwrite(buf, elementsize, BytesRead, tofile);
if (*pBytesCopied != BytesRead)
{
fclose(tofile);
fclose(fromfile);
return EXIT_FAILURE;
}
if (fclose(tofile) != EXIT_SUCCESS)
{
fclose(fromfile);
return EXIT_FAILURE;
}
if (fclose(fromfile) != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
inline int fcopy(char* szFromFilePath, char* szToFilePath, size_t* pBytesCopied)
{
FILE* fromfile = NULL;
FILE* tofile = NULL;
unsigned char buf[1024];
size_t BytesRead = 0, BytesWritten = 0;
fromfile = fopen(szFromFilePath, "rb");
if (fromfile == NULL)
{
return EXIT_FAILURE;
}
tofile = fopen(szToFilePath, "wb");
if (tofile == NULL)
{
fclose(fromfile);
return EXIT_FAILURE;
}
*pBytesCopied = 0;
do
{
BytesRead = fread(buf, sizeof(buf), 1, fromfile);
if (BytesRead <= 0)
{
// Empty file, elementsize or count is 0, or there was an error.
fclose(tofile);
fclose(fromfile);
return EXIT_FAILURE;
}
BytesWritten = fwrite(buf, BytesRead, 1, tofile);
if (BytesWritten != BytesRead)
{
fclose(tofile);
fclose(fromfile);
return EXIT_FAILURE;
}
*pBytesCopied += BytesWritten;
}
while (feof(fromfile) == 0);
if (fclose(tofile) != EXIT_SUCCESS)
{
fclose(fromfile);
return EXIT_FAILURE;
}
if (fclose(fromfile) != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
inline void RemoveExtensionInFilePath(char* szFilePath)
{
// WIN32_WINNT 0x0602 : PathCchRemoveExtension
// WIN32 : PathRemoveExtension
int idx = 0;
for (idx = (int)strlen(szFilePath)-1; idx >= 0; idx--) { if (szFilePath[idx] == '.') break; }
if ((idx > 0)&&(idx < (int)strlen(szFilePath))) memset(szFilePath+idx, 0, strlen(szFilePath)-idx);
}
inline void RemovePathInFilePath(char* szFilePath)
{
int idx = 0;
BOOL bFound = FALSE;
for (idx = (int)strlen(szFilePath)-2; idx >= 0; idx--)
{
if ((szFilePath[idx] == '/')||(szFilePath[idx] == '\\'))
{
bFound = TRUE;
break;
}
}
if ((bFound)&&(idx >= 0)&&(idx < (int)strlen(szFilePath)-1)) memmove(szFilePath, szFilePath+idx+1, strlen(szFilePath)-idx);
}
inline void GetFileNameAndFilePathAndChangeExtension(char* szFileInPath, char* szNewExtension, char* szFileOutPath, char* szFileOutName)
{
// WIN32_WINNT 0x0602 : PathCchRenameExtension
// WIN32 : PathRenameExtension
strcpy(szFileOutPath, szFileInPath);
RemoveExtensionInFilePath(szFileOutPath);
strcpy(szFileOutName, szFileOutPath);
strcat(szFileOutPath, szNewExtension);
RemovePathInFilePath(szFileOutName);
}
inline void RemoveSurroundingWhiteSpacesInString(char** pszFilePath)
{
char* szFilePath = *pszFilePath;
while ((szFilePath[strlen(szFilePath)-1] == ' ')||(szFilePath[strlen(szFilePath)-1] == '\t')||
(szFilePath[strlen(szFilePath)-1] == '\n')||(szFilePath[strlen(szFilePath)-1] == '\r'))
{
szFilePath[strlen(szFilePath)-1] = 0;
}
while ((szFilePath[0] == ' ')||(szFilePath[0] == '\t')||
(szFilePath[0] == '\n')||(szFilePath[0] == '\r'))
{