-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdstring.c
More file actions
35 lines (29 loc) · 986 Bytes
/
dstring.c
File metadata and controls
35 lines (29 loc) · 986 Bytes
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
#include <stdio.h>
#include "string.h"
// Depones Safe String Copy
// Returns the total length of the 'src' file.
// If the returned value is >= size, it means a truncation has occurred.
size_t dstrncpy(char *dst, const char *src, size_t size)
{
const char *src_start = src;
size_t left = size;
// Copy if there is space in the target buffer
if (left > 0) {
// Subtract 1 to reserve space for NULL character (\0)
while (--left != 0) {
if ((*dst++ = *src++) == '\0') {
// If the `src` (short string) ends, it's done
// The `dst` already ends with `\0`
return (src - src_start - 1);
}
}
}
// If the buffer is full but the src hasn't completed
if (size > 0) {
*dst = '\0'; // Always use null-terminate!
}
// Calculate the length of the rest of the src (for truncation check)
while (*src++)
;
return (src - src_start - 1);
}