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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned char MID(const /*unsigned*/ char* str, /*unsigned*/ char* copy, size_t str_len, size_t start, size_t NBytes) {
unsigned char ret;
if ((str != NULL) && (copy != NULL) && (start < str_len) && ((start + NBytes + 1) < str_len)) {
// strncpy(copy, (str + start), NBytes /* * sizeof(char)*/);
memcpy(copy, (str + start), NBytes /* * sizeof(char)*/);
copy[NBytes] = '\0';
ret = 1;
} else {
ret = 0;
}
return ret;
}
/*unsigned*/char* MID_1(const /*unsigned*/ char* str, size_t str_len, size_t start, size_t NBytes) {
char* ret;
if ((str != NULL) && (start < str_len) && ((start + NBytes + 1) < str_len)) {
ret = malloc((NBytes + 1) * sizeof(char));
if (ret != NULL) {
strncpy(ret, (str + start), NBytes /* * sizeof(char)*/);
// memcpy(ret, (str + start), NBytes /* * sizeof(char)*/);
ret[NBytes] = '\0';
}
} else {
ret = NULL;
}
return ret;
}
unsigned char MID_2(const /*unsigned*/ char* str, /*unsigned*/ char** copy, size_t str_len, size_t start, size_t NBytes) {
unsigned char ret;
if ((str != NULL) && (copy != NULL) && (start < str_len) && ((start + NBytes + 1) < str_len)) {
(*copy) = malloc((NBytes + 1) * sizeof(char));
if (((*copy) != NULL)) {
// strncpy((*copy), (str + start), NBytes /* * sizeof(char)*/);
memcpy((*copy), (str + start), NBytes /* * sizeof(char)*/);
(*copy)[NBytes] = '\0';
ret = 1;
} else {
ret = 0;
}
} else {
ret = 0;
}
return ret;
}
int main(int argc, char* argv[])
{
/*unsigned*/ char buf[64] = "SUNMONTUEWEDTHUFRISAT\0";
/*unsigned*/ char buf1[64] = ".....................\0";
/*unsigned*/ char* buf2 = NULL;
if ( MID(buf, buf1, 64, 6, 3) ) {
printf("1) %3s\n", buf1);
} else {
printf("1) problem\n");
}
if ( MID(buf, buf1, 64, 9, 60) ) {
printf("2) %3s\n", buf1);
} else {
printf("2) problem\n");
}
buf2 = MID_1(buf, 64, 9, 9);
if (buf2 != NULL) {
printf("3) %3s\n", buf2);
free(buf2);
} else {
printf("3) problem\n");
}
if ( MID_2(buf, &buf2, 64, 12, 3) ) {
printf("4) %3s\n", buf2);
free(buf2);
} else {
printf("4) problem\n");
}
return EXIT_SUCCESS;
} |