Last active
December 30, 2015 11:19
-
-
Save yorkie/7821598 to your computer and use it in GitHub Desktop.
a more geek function for the socket/recv 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
char *imap_recv(int fd, size_t size) { | |
size_t cursor = 0; | |
int rc; | |
char *buffer = (char *)malloc(sizeof(char)*size); | |
char *result = (char *)malloc(sizeof(char)*size); | |
while (rc = recv(fd, buffer, size, 0)) { | |
// if a message is less than the current size, it will return more data for fill in this pool. so I use \0 to avoid it. | |
buffer[rc] = '\0'; | |
char *temp_str = buffer; | |
char *temp_ptr = (char *)realloc(result, sizeof(char)*(cursor++)*size+rc); | |
if (temp_ptr == NULL) { | |
free(buffer); | |
free(result); | |
return NULL; | |
} | |
if (result != NULL) { | |
strcpy(temp_ptr, result); | |
strcat(temp_ptr, temp_str); | |
result = temp_ptr; | |
} else { | |
strcpy(result, buffer); | |
}; | |
// break | |
if (rc < size) break; | |
} | |
free(buffer); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment