0
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define DEVICE "/dev/ISMTestDevice"

int main()
{
        int i, fd;
        char ch, wbuf[100], rbuf[100];

        fd = open(DEVICE, O_RDWR);

        if(fd < 0) {
                printf("Device file opening error.\n");
                exit(1);
        }
        printf("r = read from device\n w = write to device\n enter command:");
        scanf("%c", &ch);

        switch(ch)
        {
                case 'w':
                        printf("enter data less than 100 characters:");
                        scanf("%[^\n]", wbuf);
                        write(fd, wbuf, sizeof(wbuf));
                        break;

                case 'r':
                        read(fd, rbuf, sizeof(wbuf));
                        printf("data read from device:%s\n", rbuf);
                        break;
        }

        return 0;
}

The above program compiles without any errors. But when I execute the program with case 'w', the control is not coming to the "scanf("%[^\n]", wbuf);" statement and instead of that command prompt is appearing as like below.

output:

[root@localhost char_cdev]# ./a.out 
r = read from device
w = write to device
enter command:w
enter data less than 100 characters:[root@localhost char_cdev]#
  • The first `scanf` reads only the `w`, but not the newline after it. The `scanf("%[^\n]", wbuf)` will then read the zero bytes to the next newline. (You stil need to press return after typing the "w", because input is buffered until a newline is read.) Do a dummy scan `scanf("%*[^\n]")` to eat the newline. – M Oehm Oct 12 '19 at 19:23
  • 2
    Because `"%c"` left the newline in the buffer, and `"%[^\n]"` doesn't skip whitespace. Typically, you always want to skip leading whitespace. To do that, put a space character before the conversion, for example `" %c"` and `" %[^\n]"` – user3386109 Oct 12 '19 at 19:23
  • https://stackoverflow.com/questions/14873542/use-scanf-with-regular-expressions – OznOg Oct 12 '19 at 19:24
  • Thanks for your replies and the program flow is working the way it intends. – Bhaskara Rao Santa Oct 13 '19 at 11:36

0 Answers0