Last active
August 13, 2019 11:09
-
-
Save gustavorv86/c1168041864782d75a618364a039808b to your computer and use it in GitHub Desktop.
String append function written in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define MAX_BUF 128 | |
int string_append(char * buffer, size_t buffer_size, const char * string) { | |
size_t buffer_len = strlen(buffer); | |
size_t free_size = buffer_size - buffer_len; | |
size_t string_len = strlen(string); | |
if(free_size > string_len) { | |
strncpy(buffer + buffer_len, string, string_len); | |
return string_len; | |
} else { | |
return -1; | |
} | |
} | |
int main() { | |
char string_all[MAX_BUF]; | |
memset(string_all, 0x00, sizeof(string_all)); | |
char string[64]; | |
int count = 0; | |
int bytes_copied = 0; | |
do { | |
snprintf(string, sizeof(string), "%d: Hello World!\n", ++count); | |
bytes_copied = string_append(string_all, sizeof(string_all), string); | |
} while(bytes_copied > 0); | |
printf("%s\n", string_all); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment