-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathex_5-5.c
124 lines (91 loc) · 2.45 KB
/
ex_5-5.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <string.h>
#include <stdio.h>
/* print contents of array */
void print_array(char s[])
{
int i;
for(i = 0; i < strlen(s); i++)
printf("%c", s[i]);
printf("\n");
}
/*
Copy at most n chars of string source into string dest.
Pad with '\0' if source has fewer chars than dest.
*/
char *ss_strncpy(char *dest, const char *source, int n)
{
char *d = dest;
if(n >= 0 || n == '\0')
{
while(--n >= 0 && (*dest++ = *source++) != '\0')
continue;
while(--n > 0)
*dest++ = '\0';
}
return d;
}
/*
Appends n chars of src into the end of dest.
If null encountered before n, then copy null and no more.
If n is zero or negative, then function has not effect.
*/
char *ss_strncat(char *dest, const char *source, size_t n)
{
while(*dest) { ++dest; } // find pointer val for end of string s
while((--n >= 0) && (*dest++ = *source++) != '\0');
return dest;
}
/*
Compares contents of string s1 with contents of s2.
If s1 < s2 returns < 0
If s1 == s2 returns 0
If s1 > s2 returns > 0
*/
int ss_strncmp(const char *s1, const char *s2, size_t n)
{
while(--n >= 0 && *s1 != '\0' && *s2 != '\0')
{
if(*s1++ == *s2++) { continue; }
if(*s1 > *s2)
return 1;
else
return -1;
}
return 0;
}
int main()
{
char source[] = { "Destination after..." };
char dest[] = { "This is the destination before..." };
print_array(dest);
char *ans;
ans = strncpy(dest, source, 20);
printf("%p\n", ans);
print_array(dest);
printf("\n\n");
char source2[] = { "Destination after..." };
char dest2[] = { "This is the destination before..." };
print_array(dest2);
ss_strncpy(dest2, source2, 20);
printf("%p\n", ans);
print_array(dest2);
char info[] = { "Data To Append. " };
char buffer[50] = { "Beginning of Buffer. " };
int i;
for(i = 0; i <= 2; ++i)
{
strncat(buffer, info, strlen(info));
print_array(buffer);
}
printf("\n");
char smaller[] = { "12345" };
char bigger[] = { "67890" };
int size_ans;
size_ans = ss_strncmp(smaller, bigger, 3);
printf("%d\n", size_ans);
size_ans = ss_strncmp(bigger, bigger, 3);
printf("%d\n", size_ans);
size_ans = ss_strncmp(bigger, smaller, 3);
printf("%d\n", size_ans);
return 1;
}