-
Quick question
Sorry, I'm having a huge brainfart and need some help. I have the following code and I'm trying to read a string from the user (maximum of three strings) then execute those commands. Everytime I compile, I get a segmentation fault. Can someone out there help me find my mistake?
#include <stdio.h>
#include <string.h>
int main() {
int i, j, times = 1;
char choice;
char *command[3];
char *temp;
for(i=0;times < 3;i++) {
printf("Please input a valid UNIX command: ");
/* I get seg. Fault on the following line */
scanf("%s", command[i]);
/* gets(*command[i]); */
printf("You have successfully entered %d command(s) out of a possible /
%d commands.\n");
printf("Would you like to enter another command? (y/n): ");
scanf("%c" ,&choice);
if(choice == 'Y' || choice =='y') {
times++;
continue;
}
if(choice == 'N' || choice == 'n')
break;
else
return 0;
} /* End loop */
for(i=0;times <= 3;i--) {
strcpy(command[i], temp);
for(j=0;!isspace(*command[j]);j++)
temp[j] = *command[j];
printf("%% %s\n", temp);
system(command[i]);
} /*End for loop*/
-
This is the easy way to do it!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int i;
for (i = 0; i < argc, ++i)
system(argv[i]);
return 0;
}
Your code has a number of bugs. It uses gets and using scanf with %s and no
field specifier is just as bad. You should use fgets.
command[3] should be command[3][MAX_CMD_SIZE]
If I'm correct the best way to do this is to avoid the 2D array with something
like this
Code:
char command[MAX_CMD_SIZE];
while(fgets(comand, sizeof command, stdin) != NULL) {
printf("Enter command EOF to quit: ");
fflush(stdout);
system(command);
}
-
Brainfart... my seventh grade history teacher used that word...
-
Thanks for all the help guys, I ended up doing it with 2D char arrays, but it's done and it works and that's all that matters!