I don't understand getting input in C. I have the following code which is producing a segmentation fault:
int main(int argc, char *argv[]){
while (fgets(buffer, MAX_LEN + 1, input) != NULL) {
get_command(t, buffer);
}
return 0;
}
and
static void get_command(Table *t, char *command) {
COMMAND command_name = 0;
char *valid_args_str[] = {"aa","bb"};
int arg_counter = 1;
scanf("%s", command);
if (!strncmp(command, "in", 2)) {
command_name = INSERT;
while(arg_counter){
printf("whileloop reached, arg_counter is %d", arg_counter);
scanf("%s", valid_args_str[arg_counter - 1]);
}
.
.
.
}
The print statement isn't even being evaluated before i get a segmentation fault. Whats going on?
What is while (fgets(buffer, MAX_LEN + 1, input) != NULL)
doing?
What is scanf()
doing? Can I have one scanf(
) follow by another? I intent for the arguments to be on the same line.
Thanks!
UPDATE:
Here is updated code. Still same problem. Hopefully this will be a more complete clip:
typedef enum { INSERT = 1, SEARCH, DELETE, RESET, DISPLAY} COMMAND;
static void get_command(Table *t, char *command) {
COMMAND command_name = 0;
char valid_args_str[] = {"aa","bb"};
int arg_counter = 0;
char other_buffer[MAX_LEN + 1];
sscanf(command, "%s", other_buffer);
if (!strncmp(other_buffer, "in", 2)) {
command_name = INSERT;
while(++arg_counter){
printf("whileloop reached, arg_counter - 1 is %d\n", arg_counter - 1);
scanf("%s", valid_args_str[arg_counter - 1]);
}
} else if (!strncmp(other_buffer, "se", 2)) {
.
.
.
execute_comm(t, command_name, valid_args_str);
}
static void execute_comm(Table *t, COMMAND command, char *args[]){
switch(command){
case INSERT:
insert(t, args[0], args[1]);
break;
.
.
}
and here is my main:
int main(int argc, char *argv[]){
FILE *input;
char buffer[MAX_LEN + 1];
input = stdin;
if(argc > 2){
fprintf(stderr, "%s", "Too many arguments");
perror("Too many arguments");
exit(EX_OSERR);
} else if (argc == 2){
if ((input = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "%s", "error opening files");
perror("error opening file");
exit(EXIT_FAILURE);
}
}
while (fgets(buffer, MAX_LEN + 1, input) != NULL) {
get_command(t, buffer);
}
fclose(input);
return 0;
}
What I want to happen is for it to be able to read a file like this:
insert beans lima
delete beans
etc. and from standard input. Some commands have two arguments, some have one, and some none.
Thanks again