简体   繁体   中英

Redirecting input to C program

I have this 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 is a version of the command cat but in this program i give as an argument the number of bytes each read will read. Now i have a file b.txt and i want to redirect the file content to the program as input so i used this

./mycat 1024 < b.txt

But nothing happens, the program keeps waiting for me to type some text, like if i did ./mycat 1024 . Why is not the redirection working?

You have to read from the stdin. But you are reading the contents from stdout. So, only you are blocked to entering the input.

The file descriptor for stdin is 0. and stdout is 1. If you are confusing with these 1 and 0. You can use the macros for stdin and stdout file descriptors.

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

STDIN_FILENO     -- Standard input file descriptor
STDOUT_FILENO    -- Standard output file descriptor
STDERR_FILENO    -- Standard error file descriptor

So, change the code as like below. It will work as you 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM