-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstr.c
More file actions
70 lines (58 loc) · 1.48 KB
/
str.c
File metadata and controls
70 lines (58 loc) · 1.48 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
#include "str.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
String *newString(char *str, size_t n) {
String *string = malloc(sizeof(String));
string->length = n == 0 ? strlen(str) : n;
string->available = string->length * 2 + 1;
string->data = malloc(string->available);
if (string->data == NULL) {
return NULL;
}
if (n == 0) {
strcpy(string->data, str);
} else {
strncpy(string->data, str, n);
}
return string;
}
void appendString(String *string, char *str) {
size_t length = strlen(str);
bool reallocate = false;
while (length + string->length > string->available) {
string->available *= 2;
reallocate = true;
}
if (reallocate) {
char *aux = string->data;
string->data = realloc(string->data, string->available + 1);
if (string->data == NULL) {
string->data = aux;
}
}
strcat(string->data, str);
string->length += length;
}
void appendStringN(String *string, char *str, size_t n) {
size_t length = strlen(str);
bool reallocate = false;
while (length + n > string->available) {
string->available = string->available * 2 + 1;
reallocate = true;
}
if (reallocate) {
char *aux = string->data;
string->data = realloc(string->data, string->available + 1);
if (string->data == NULL) {
string->data = aux;
}
}
strncat(string->data, str, n);
string->length += length;
}
void deleteString(String *string) {
free(string->data);
free(string);
}