c - How to pipe data to a program which calls scanf() and read() in Linux -
i have c programme looks this:
#include <stdio.h> #include <unistd.h> int main() { int n; char str[16]; scanf("%d", &n); printf("n: %d\n", n); int count = read(stdin_fileno, str, 16); printf("str: %s\n", str); printf("read %d bytes\n", count); } if pipe info programme using command like
(echo -en '45\n'; echo -en 'text\n') | ./programonly scanf() reads data. read() reads 0 bytes.
in other words, programme outputs
n: 45 str: read 0 byteshow can pipe info both scanf() , read()?
edit: sorry, should have clarified: i'm looking way without modifying source. people answered , commented anyway.
it not recommended @ utilize both file descriptor functions (read) , stream functions (scanf) same file descriptor. functions using file * (i.e. fread/fprintf/scanf/...) buffering info while functions using file descriptors (i.e. read/write/...) not utilize buffers. in case, easiest way prepare programme utilize fread instead of read. programme may like:
#include <stdio.h> #include <unistd.h> int main() { int n; char str[16]; scanf("%d", &n); printf("n: %d\n", n); int count = fread(str, 16, 1, stdin); printf("str: %s\n", str); printf("read %d bytes\n", count); } in original example, scanf has read input ahead , stored in buffer. because input short , available exclusively read buffer , invocation of read had nil more read.
this not happen when come in input straight terminal, because scanf not buffer info beyond 1 line when reading terminal device. not happen if create time pause in piped input illustration command:
(echo -en '45\n'; sleep 1; echo -en 'text\n') | ./program c linux unix pipe
No comments:
Post a Comment