error handling - C: using the system() command -
i'm writing program acts simple shell. users call program command line , prompted enter commands sent os completion. should run until user enters "done", @ point program should break. i'm running problem entering done - program quits should, prints
sh: -c: line 0: syntax error near unexpected token `done' sh: -c: line 0: `done' to terminal before finishing execution. here's code i've written applies:
char isdone[] = "done\n"; //fgets stores new line character command line { printf(">>"); //print prompt each time through loop fgets(command, 50, stdin); //get line terminal system(command); } while (strcmp(command, isdone) != 0); //break loop if user types in done i think error has fact "done" not valid unix command, i'm not sure how deal error. tried solving problem following fix:
if(system(command) == -1){ printf("the os doesn't recognize command"); } else system(command); but didn't solve problem or printing errors screen, , created second problem of printing commands/errors twice - once in if conditional block, , once in else block. how can solve problem?
edit homework question requires using do-while. there solution uses do-while?
the do...while construct executes body before loop condition checked. time loop "realizes" user entered done, has tried execute input command inside loop body.
the clearest way fix use break:
while (1) { fgets(command, 50, stdin); if (!strcmp(command, isdone)) break; system(command); } the reason structure way each iteration consists of both actions should done before condition (reading in user input) , actions should done after condition (executing command system()). because of this, neither do...while or simple while allow structure code intuitively. break keyword gives way put loop's termination condition in middle of loop body.
Comments
Post a Comment