So I am trying to take the users input using read(). The while loop runs until ctrl d is entered in linux terminal and the input is stopped. I wrote some code and it works, but the problem I am running into is that I don't know how to take exactly whats in the input and how to use it.
In the code below, right after if(buff[offset] == '\n')
(runs the given input, and after its finished clears the buffer and moves on to the next input) I don't know how to go into the 3 possible cases of input and also I don't know how to get the number from the second case:
- "e" - exit the program
- "p N" - do something, N is a number which I also need to get into a variable (I think that
buff[offset-1]
should get the number but I am not quite sure.) - everything else - print a message
Code:
int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
const size_t read_size = 1; // set chunk size
size_t size = read_size;
size_t offset = 0;
size_t res = 0;
char *buff = malloc(size 1);
*buff = '\0';
while((res = read(fd, buff offset, read_size)) > 0) // read from stdin and save to buff
{
if(buff[offset] == '\n')
{ // THIS PART
buff[offset] = '\0';
if(buff == "e")
{
// exit the program
return 0;
}
else if(buff == "p")
{
// do sth
}
else
{
// print a message
}
// reset the buffer (free its memory and allocate new memory for the next input)
offset = 0;
size = read_size;
free(buff);
buff = NULL;
buff = malloc(size 1);
*buff = '\0';
}
else
{
offset = res;
buff[offset] = '\0';
if (offset read_size > size)
{
size *= 2;
buff = realloc(buff, size 1);
}
}
}
If this isn't possible with read() I can try with something else like fgets() perhaps?
CodePudding user response:
if(buff == "p")
This line checks if the string buff
is stored at the same address as the string "p"
. However, you don't want to check if the strings are stored at the same address, but if they have the same content.
... how would strcmp() work ...
Using strcmp()
you can check if two strings are identical:
if(!strcmp(buff, "e"))
"p N" ... since the number N could be any number?
Simply check if the first character of buff
is 'p'
:
if(buff[0] == 'p')
Note that single quotes ('
) are used instead of double quotes ("
) for character constants (in contrast to string constants).
CodePudding user response:
As I described in my comment above, here is a full answer:
int main(void)
{
char line[100], cmd;
int num, cnt;
while(fgets(line,sizeof(line),stdin)) != EOF) {
cnt = sscanf(line," %c %d",&cmd,&num);
if (cnt == 0) {
// empty line, no command
} else if (cmd == 'e') {
// exit the program
break;
} else if (cmd == 'p' && cnt == 2) {
// no something with num
} else {
// print a message
}
}
return 0;
}