1

I'm working on a portion of a program that deals with overwriting files in a directory. Overwriting the files is easy... but apparently making the prompt that asks users if they wish to overwrite the file is not. For example: if I wish to overwrite two files (fileOne.txt, fileTwo.txt), I need to prompt the user twice (once for each file). With my current prompt, if I prompt the user to overwrite fileOne.txt, both fileOne.txt and fileTwo.txt will be overwritten. If there are more than two files to overwrite, it will overwrite only two consecutive files. I believe it has something to do with hitting "Enter", but I just have no clue...

if(((int)getHeader.deleted - 48) == 0) {
        if(access(getHeader.file_name, F_OK) != -1) { /* File exists in directory, check for overwrite */
            printf("%s already exists. Would you like to overwrite it? (y/n)\n", getHeader.file_name);
            scanf("%c", buffer);
            while(!validResponse) {
                if(buffer[0] == 'y' || buffer[0] == 'Y') {
                    validResponse = 1;
                    printf("DO SOMETHING - Files will be overwritten\n");
                } else if(buffer[0] == 'n' || buffer[0] == 'N') {
                    validResponse = 1;
                    printf("DO SOMETHING - File will be skipped\n");
                } else {
                    printf("Invalid response... Would you like to overwrite %s? (y/n)\n", getHeader.file_name);
                    scanf("%c", buffer);
                } /* End if else */
            } /* End while */
        } /* End if */
    } /* End if */ 
kubiej21
  • 700
  • 4
  • 14
  • 29

1 Answers1

3

When you read a single char you leave a newline in stdin you need to consume that:

scanf("%c", buffer);
getchar();  // consume the leftover '\n'

would do it, or in just oneline:

scanf(" %c", buffer); // the space will tell it to skip any "white space" characters


With just the code snippet you have here, if there was an invalid character entered at the first prompt, it would seem to skip by the else's scanf (in reality it's reading the first leftover '\n') and it will loop around again to get input.

Without seeing the rest of the code, presumably you have this all in a loop and that's why it's skipping over files in 2s. ('Y', then '\n')

Mike
  • 47,263
  • 29
  • 113
  • 177
  • Alternately, you could put a blank space in the format string: `scanf(" %c", buffer);` - this will tell `scanf` to skip leading whitespace and read the next *non*-whitespace character. – John Bode Mar 01 '13 at 17:48
  • getchar(); did the trick. Thanks for the help – kubiej21 Mar 01 '13 at 17:51
  • @JohnBode - Yup, lots of possibilities, I added yours as well. – Mike Mar 01 '13 at 17:51