cs-3516-assignment-1/common/socket_helper.c

27 lines
840 B
C

#include "socket_helper.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *get_all_remote_parts(int socket_fd) {
int current_size = BUFFER_SIZE;
char *result = NULL;
char *buffer = malloc(BUFFER_SIZE * sizeof(char));
while (read(socket_fd, buffer, BUFFER_SIZE) > 0) {
//Allocate a new result buffer if we need to, otherwise grow the existing one.
if (result == NULL) {
result = malloc(BUFFER_SIZE);
} else {
int old_size = current_size;
current_size += BUFFER_SIZE;
char *new_result = malloc(current_size * sizeof(char));
strncpy(new_result, result, old_size);
free(result);
result = new_result;
}
memcpy(result, buffer, BUFFER_SIZE);
}
free(buffer);
return result;
}