-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilities.h
More file actions
104 lines (90 loc) · 1.99 KB
/
utilities.h
File metadata and controls
104 lines (90 loc) · 1.99 KB
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
#ifndef __UTILITIES_H
#define __UTILITIES_H
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_WORDS 20
#define MAX_STRING_LEN 20
void errore(char* s, int n);
char** split(char* s, char* seps);
char* readCSV (FILE* fp, char sep);
char* inputStr();
int str2int(char*s);
char* int2str(int n);
char* strrev(char* sx);
char* mystrdup(char* s);
void errore(char* s, int n) {
printf("ERROR in %s - %d - %s\n", s, errno, strerror(errno));
printf("return code: %d\n", n);
exit(n);
}
char** split(char* s, char* seps) {
char* temp[MAX_WORDS+1];
char* s1 = strdup(s);
char* token = strtok(s1, seps);
int i = 0;
for(i=0; token != NULL ; i++) {
temp[i] = strdup(token);
token = strtok(NULL, seps);
}
temp[i] = NULL;
free(s1);
char** ret = (char**) malloc(sizeof(char*) * i);
for( i=0; *(ret+i) = temp[i]; i++) { }
return ret;
}
char* readCSV (FILE* fp, char sep) {
char temp[MAX_STRING_LEN +1];
int i = 0;
for(; ((temp[i] = fgetc(fp)) != sep) &&
(temp[i] != '\n') &&
(temp[i] != EOF) ;
i++) { }
if (i==0) return NULL;
temp[i] = '\0';
return strdup(temp);
}
char* inputStr() {
char temp[MAX_STRING_LEN +1];
int i = 0;
for(; (temp[i] = getchar()) != '\n' ; i++) { }
temp[i] = '\0';
return strdup(temp);
}
int str2int(char*s) {
int ret = 0;
for(;*s; s++)
ret = *s -'0' + ret * 10;
return ret;
}
char* int2str(int n) {
char buffer[MAX_STRING_LEN];
int i;
for(i=0; n; i++) {
int resto = n % 10;
buffer[i] = '0' + resto;
n = n / 10; /* la divisione tra interi restituisce un intero */
}
buffer[i] = '\0';
strrev(buffer);
return strdup(buffer);
}
char* strrev(char* sx) {
char* saved = sx;
char* dx = sx + strlen(sx) -1;
for(; sx < dx; sx++, dx--) {
char temp = *sx;
*sx = *dx;
*dx = temp;
}
return saved;
}
char* mystrdup(char* s) {
char* s2 = (char*) malloc(sizeof(char) * (strlen(s) +1));
char* ret = s2;
for(; *s2 = *s; s++, s2++) { }
return ret;
}
#endif /* __UTILITIES_H */