-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_server_utils.c
More file actions
executable file
·68 lines (60 loc) · 2.38 KB
/
client_server_utils.c
File metadata and controls
executable file
·68 lines (60 loc) · 2.38 KB
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
/* File of shared functions between the server and the client
* Author: YOUR NAME HERE */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "client_server_utils.h"
/* Function that finds the index at which the newline character exists in the
* message. Returns -1 if no newline exists in the string. START is in the
* index in the start at which the search should begin. */
int find_message_end (char *msg, int start) {
int end = start;
char *p = msg;
for(int n = 0; n < start; n++)
p++;
while(*p != 0)
{
if(*p == '\n'){
return end;
}
end++;
p++;
}
return -1;
}
/* Function that takes a char * which is a buffer of data received. This
* buffer contains 1 or MESSAGES where a message is defined as being a
* series of characters ending in a newline. Its other parameter, end,
* is the length of the first message in the buffer. If MESSAGES contains more
* than one message then these messages WILL NOT be separated by a null
* terminator. However, MESSAGES will always be terminated by a null
* terminator. The function should malloc and outputs a new char * consisting
* of the first message (which needs end + 1 Bytes). It should also update
* MESSAGES so that its contents are a string that contains any remaining
* messages and just a null terminator if no more messages remain. You may
* want to use some combination of strlen, strcpy, and strncpy. As an
* important note if you elect to attempt to use strcpy or strncpy for this
* function the dst pointer and the src pointer cannot contain addresses that
* will overlap. This means the address of any information from src cannot be
* the same as an address that gets written to in dst */
char *generate_message (char *messages, int end) {
if(messages != NULL)
{
char *p;
if((p = (char*) malloc(end+1)) == NULL){
allocation_failed();
}
strncpy(p, messages, end);
p[end] = '\0';
char temp[1025];
strcpy(temp, messages+end);
strcpy(messages, temp);
return p;
}
return NULL;
}
/* Function that terminates the program when a malloc fails. */
void allocation_failed () {
fprintf (stderr, "Unable to allocate enough memory\n");
exit (1);
}