Created
April 16, 2019 10:30
-
-
Save haxpor/ec923e602e8d5b6b176cbda9f1160230 to your computer and use it in GitHub Desktop.
equivalent of fgets() but works on string instead of file
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
// equivalent to fgets() but works on string instead of file | |
/* | |
* Equivalent to fgets() but operate on string instead of file. | |
* It will read string upto `dst_size` or stop reading whenever find newline character, | |
* then return string so far as read via `dst_str`. | |
* | |
* `offset` will be updated according to the current number of bytes read. | |
* First call should always set it to 0, then consecutive call will be automatically updated by | |
* this function, just re-supply it in the function call. | |
* | |
* At last, it will stop whenever it has read all of the bytes from the `input_str`. | |
* | |
* \param dst_str destination string as output | |
* \param dst_size up to number of size to read for destination string | |
* \param input_str input string to read | |
* \param offset pointer to offset number for consecutive call | |
* \return string as read starting from `offset` and up to `dst_size`. It returns NULL when all of `input_str`'s bytes has been read. | |
*/ | |
static char* sgets(char* dst_str, int dst_size, const char* input_str, int* offset) | |
{ | |
int size_count = 0; | |
const int of = *offset; | |
if (of > strlen(input_str)) | |
return NULL; | |
for (int i = 0; i<dst_size; ++i) | |
{ | |
char c = input_str[of + i]; | |
if (c == '\n') | |
{ | |
dst_str[i] = c; | |
dst_str[i+1] = '\0'; | |
++size_count; | |
break; | |
} | |
else if (c == '\0') | |
{ | |
dst_str[i] = c; | |
++size_count; | |
break; | |
} | |
else | |
{ | |
dst_str[i] = c; | |
++size_count; | |
} | |
} | |
// set offset back for future calls | |
*offset = *offset + size_count; | |
return dst_str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment