I have a short main that interacts with the user, grabbing commands to call on files passed as arguments to the program. The program queries the user for a command, gets the command, and then processes. If the user types 'n' the program goes to the next file. On the second file, and I'm assuming the following files, the query printf prints twice. Anyone have an idea why that happened?
2nd EDIT: Upon further investigation i've found that it is carrying out the command related the the user-entered char, and then for some reason it loops again and calls execute_option with a blank, perhaps the \n char, which calls the default case. Any idea how to avoid this? I've used a for(;; ) with a break or exit before with no trouble, but this while loop structure seems to be posing an issue.
for example with "a.out wut huh" (n is next file, q is quit program).
Code:
for the file ``wut'': please enter a command command:
n
for the file ``huh'': please enter a command command:
for the file ``huh'': please enter a command command:
q
Code below: I've chopped out includes. They are all fine. EDIT: I realize the bottom of main got chopped off, ignore that. The loops are the important parts.
Code:
int execute_choice(char c, char *filename)
{
switch(c)
{
case('c'): list_file(filename); return 1;
case('d'): copy_file(filename); return 1;
case('r'): rename_file(filename); return 1;
case('u'): remove_file(filename); return 1;
case('t'): truncate_file(filename); return 1;
case('a'): append_file(filename); return 1;
case('l'): tail_file(filename); return 1;
case('m'): change_permissions(filename); return 1;
case('x'): change_access(filename); return 1;
case('n'): return 0;
case('q'): exit(0);
default: return 1;
};
}
int main(int argc, char *argv[])
{
if(!(argc>1))
{
fprintf(stderr, "Usage: wash <file1> <file2>...\n");
exit(-1);
}
int go_next = 1;
for(argv++; *argv != NULL; )
{
char command;
while(go_next == 1)
{
printf("for the file ``%s'': please enter a command command:\n", *argv);
command = getchar();
go_next = execute_choice(command, *argv);
}
argv++;
go_next = 1;
}
Thanks folks.