Using getchar () after reading ()

c to grab the keyboard. After entering the code when pressing the arrow key / esc. At the same time, I want to read whole words, that's user inputs and they should be shown on stdout .

char pp = 0;
char p = 0;
while( (i = read(0, &c, 1)) == 1) {
if (pp == 033 && p == 0133 && (c &= 255) == 0102) /* DOWN */ break;
if (c == 0177) /* ASCII DELETE */ break;
printf( "%o, %o, %o\t%s\n\r", pp, p, c, &c);
pp = p;
p = c; 
}
...
...
getchar(); //I want to capture here what was entered before
           //  **return key** was pressed.

      

But this code doesn't work if I remove '\ n'. I want stdout to behave like a normal shell.

+2


source to share


3 answers


printf(3)

passes through buffered I / O <stdio.h>

that includes fputs(3)

and fputc(3)

. You are seeing normal line buffering behavior. You can beat this buffering as stated in setbuf(3)

, however, since you don't want it in the first place and you are already using a direct kernel call ( read(2)

) to read, why not change your logic a bit to call the kernel directly with write(2)

?

char buffer[100];

int n;

n = snprintf(buffer, sizeof buffer, "format string...", args...);
write(1, buffer, n)

      



And if you wanted, you could define your own directPrintf to make it easier:

#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>

int directPrintf(const char *format, ...)
{
va_list ap;
char buffer[200];

    va_start(ap, format);
    int n = vsnprintf(buffer, sizeof buffer, format, ap);
    va_end(ap);
    return write(1, buffer, n);
}

      

+2


source


getchar()

is most likely implemented in terms read()

that reads much more than 1 byte (usually an integer PIPE_BUF

, or 4096 bytes). It then maintains a private cursor in that buffer, fetches bytes as needed.

This is done because it read()

has nontrivial overhead associated with simply calling it.



printf()

and fwrite()

(etc.) also buffers for the same reason ( write()

has non-trivial overhead). The call fflush(stdout)

will result in a call to write()

something that was buffered but not sent to the main I / O port.

Finally, you got \n\r

back; he almost certainly should be\r\n

0


source


insert

setbuf( stdout, NULL);

      

somewhere in the beginning and remove the \ n.

0


source







All Articles