dimanche 1 mars 2015

Parse User Input Strtok



I am trying to parse user input and I am really confused, because I'm 2 weeks into trying to learn C. I guess I just don't understand what strtok is doing because I keep getting a seg fault. I am trying to take user input (either by command line or fgets) and send that into my parse_command function and from there, separate it into commands and arguments. Could someone help me understand what is going on in the program and why it isn't working and maybe what to try to get it to work? I think if I could just understand this, I could get a lot further in my program. I have searched how to do this, which is what caused me to use strtok, but apparently I am not using it right. Thanks for your help.



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdbool.h>
#include <time.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/wait.h>
#define BUFSIZE 1024
#define CSTRSIZE 100
#define CMDSIZE 30
#define DEBUG 1
int parse_command(char* line, char** cmd1, char** cmd2, char* infile, char* outfile){
_Bool pipe_found = false;
_Bool input_found = false;
int redirection = 0;
int i = 0;
char *save[CMDSIZE];
if( (strlen(line) >=4) && (line[0] == 'q') && (line[1] == 'u') && (line[2] == 'i') && (line[3] == 't')){
return 0;
}

while(line[i] != '\0'){

if(line[i] == '|'){
pipe_found = true;
}else if(line[i] == '<'){
input_found = true;
}else if(line[i] == '>' && redirection == 0){
if(line[i+1] == '>'){
redirection = 2;
}else{
redirection = 1;
}
}
i++;
}
char *pch;
if(pipe_found == false && redirection == 0 && input_found == false){
int i = 0;
pch = strtok (line," ");
while (pch != NULL) {
cmd1[i] = pch;

pch = strtok (NULL, " ,.-");
}
while(cmd1[i] != NULL){
printf("%s", cmd1[i]);
i++;
}
}
if(pipe_found == true){
if(input_found == true){
return 6;
}
else if(redirection >0){
return 9-redirection;
}else{
return 5;
}
}else{
if(input_found == true){
return 2;
}else if(redirection >0){
return 5-redirection;
} else{
return 1;
}
}

}
int main(int argc, char *argv[]){
char *cmd1[30];
char *cmd2[30];
char *infile = NULL;
char *outfile = NULL;
int returnValue = 0;
char input[100];
if(argc == 2){
returnValue = parse_command(argv[1], cmd1, cmd2, infile, outfile);
printf("made it back\n");
}else{
printf("myshell-%%\n");
fgets (input, 100, stdin);
returnValue = parse_command(input, cmd1, cmd2, infile, outfile);
}
printf("%d\n", returnValue);
}



Aucun commentaire:

Enregistrer un commentaire