redirect - Redirecting input to C program -


i have program:

int main(int argc,char** argv){ int bytes = atoi(argv[1]); char buf[1024]; while(1){     int b = read(1,buf,bytes);     if(b<=0) break;     write(1,buf,b); } return 0; 

this version of command cat in program give argument number of bytes each read read. have file b.txt , want redirect file content program input used this

./mycat 1024 < b.txt 

but nothing happens, program keeps waiting me type text, if did ./mycat 1024. why not redirection working?

you have read stdin. reading contents stdout. so, blocked entering input.

the file descriptor stdin 0. , stdout 1. if confusing these 1 , 0. can use macros stdin , stdout file descriptors.

the following built in macros defined in unistd.h header file.

stdin_fileno     -- standard input file descriptor stdout_fileno    -- standard output file descriptor stderr_fileno    -- standard error file descriptor 

so, change code below. work expect.

#include<unistd.h> #include<stdio.h>  int main(int argc,char** argv){ int bytes = atoi(argv[1]); char buf[1024]; while(1){     int b = read(stdin_fileno,buf,bytes);     if(b<=0) break;     write(stdout_fileno,buf,b); } return 0; 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -