-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandlinereader.c
58 lines (45 loc) · 1.45 KB
/
commandlinereader.c
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
/*
// Command line reader (header file), version 1
// Sistemas Operativos, DEI/IST/ULisboa 2016-17
*/
#include <string.h>
#include <stdio.h>
/*
Reads up to 'vectorSize' space-separated arguments from the standard input
and saves them in the entries of the 'argVector' argument.
This function returns once enough arguments are read or the end of the line
is reached
Arguments:
'argVector' should be a vector of char* previously allocated with
as many entries as 'vectorSize'
'vectorSize' is the size of the above vector. A vector of size N allows up to
N-1 arguments to be read; the entry after the last argument is set to NULL.
'buffer' is a buffer with 'buffersize' bytes, which will be
used to hold the strings of each argument.
Return value:
The number of arguments that were read, or -1 if some error occurred.
*/
int readLineArguments(char **argVector, int vectorSize, char *buffer, int buffersize)
{
int numtokens = 0;
char *s = " \r\n\t";
int i;
char *token;
if (argVector == NULL || buffer == NULL || vectorSize <= 0 || buffersize <= 0)
return 0;
if (fgets(buffer, buffersize, stdin) == NULL) {
return -1;
}
/* get the first token */
token = strtok(buffer, s);
/* walk through other tokens */
while( numtokens < vectorSize-1 && token != NULL ) {
argVector[numtokens] = token;
numtokens ++;
token = strtok(NULL, s);
}
for (i = numtokens; i<vectorSize; i++) {
argVector[i] = NULL;
}
return numtokens;
}