-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdp_common.c
107 lines (81 loc) · 1.84 KB
/
mdp_common.c
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
#include "mdp_common.h"
char* substr(char* str, int start, int end)
{
int size = end - start;
char* new_str = (char*)malloc(size);
memcpy(new_str, str+start, size);
*(new_str + size) = 0;
return new_str;
}
int find_char_pos(char* str, char c, FIND_CHAR find)
{
return find(str, c);
}
int first(char* str, char c)
{
int pos = 0;
while(*str)
{
if(*str == c)
{
return pos;
}
pos++;
*str++;
}
return -1;
}
int last(char* str, char c)
{
int len = strlen(str);
int pos = len;
str = (str+len-1);
while(*str)
{
if(*str == c)
{
return pos;
}
pos--;
*str--;
}
return -1;
}
void cat(char** first_str, char* second_str)
{
int size = (strlen(*first_str) + strlen(second_str));
char* catstr = (char*)malloc(sizeof(char)*(size + 1));
memcpy(catstr, *first_str, strlen(*first_str));
memcpy(catstr + strlen(*first_str), second_str, strlen(second_str));
*(catstr + size + 1) = 0;
*first_str = catstr;
}
int get_file_length(FILE* file)
{
int length = 0;
fseek(file, 0, SEEK_END);
length = ftell(file);
fseek(file, 0, SEEK_SET);
return length;
}
MDPFile* open_file(char* name)
{
MDPFile* file = (MDPFile*)malloc(sizeof(MDPFile));
FILE* fptr;
fptr = fopen(name, "rb");
if(!fptr)
fptr = fopen(name, "wb");
int length = get_file_length(fptr);
char* buffer = (char*)malloc(length * sizeof(char) + 1);
fread(buffer, sizeof(char), length, fptr);
buffer[length] = 0;
file->fileptr = fptr;
file->size = length;
file->buffer = buffer;
return file;
}
void write_to_file(MDPFile* file, char* buffer)
{
fwrite(buffer, strlen(buffer), sizeof(char), file->fileptr);
fclose(file->fileptr);
}