LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   "for" loop acting strange... (https://www.linuxquestions.org/questions/programming-9/for-loop-acting-strange-375573/)

bulliver 10-21-2005 06:34 PM

"for" loop acting strange...
 
Well, this is probably something totally obvious, but I just can't see it...
I have some code that loops through some command-line arguments and prompts
to remove them if a flag is set (think rm -i ;)):
Code:

if (in == 1) {
        for (; optind < argc; optind++) {

                printf("rm: remove %s ('y' or 'n')? ", argv[optind]);
                fgets(&response, 2, stdin);
                if (response == 'y' || response == 'Y')
                      rm(argv[optind]);
        }
}
else
        for (; optind < argc; optind++) {
                printf("removing %s\n", argv[optind]); // printf for debug
                rm(argv[optind]);
        }

The block on the bottom (without "-i" flag set), works as expected, printing the filename then deleting it. But the top block is acting strangely., as it is not stopping to prompt for every second file it loops over. Here is sample output:
Code:

$ ./rm -i foo bar baz
rm: remove foo ('y' or 'n')? y
rm: remove bar ('y' or 'n')? rm: remove baz ('y' or 'n')? y

As you can see, it prompts for first argument fine, then prints the second, but does not prompt, then prompts for the third. It always does this no matter how many arguments. If I pass 2 arguments it prompts for the first, then prints the second prompt but does nothing (ie: the program exits...).

The files that do get prompted are being deleted or not according to the y or n as they should.

Originally I was using scanf instead of fgets, but behavior was exactly the same.

Any ideas? thanks...

jlliagre 10-21-2005 07:05 PM

This line is obviously the reason.
Code:

fgets(&response, 2, stdin);
Try replacing it with:
Code:

response=getchar();
getchar(); /* skip Enter */


bulliver 10-22-2005 02:29 PM

Thanks jlliagre,

I did not get mail notification of your response, so I ended up figuring it out myself. Indeed, the line-feed was being passed immediately to the next fgets in the loop...

This is working for me now...
Code:

do {             
            response = getchar();
} while (response == '\n');

Thanks again...

I was using fgets, because the manpage says:
"fgets() reads in at most one less than size characters from stream"
as I am passing "2" I thought it would give me a single character 'y' or 'n'.

jlliagre 10-23-2005 03:14 AM

There was another issue with your first code, you were passing a pointer to a single character to fgets, but fgets was writing a null to the memory just after this location, overwriting whatever other variable that may be there.


All times are GMT -5. The time now is 05:45 PM.