简体   繁体   English

将输入重定向到C程序

[英]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. 这是命令猫的一种版本,但是在此程序中,我给出了每次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 现在我有一个文件b.txt ,我想将文件内容重定向到程序作为输入,所以我用了这个

./mycat 1024 < b.txt

But nothing happens, the program keeps waiting for me to type some text, like if i did ./mycat 1024 . 但是什么也没发生,程序一直在等我输入一些文本,就像我./mycat 1024 Why is not the redirection working? 为什么重定向不起作用?

You have to read from the stdin. 您必须阅读标准输入。 But you are reading the contents from stdout. 但是您正在从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. stdin的文件描述符为0。stdout为1。如果您将它们与1和0混淆。可以将宏用于stdin和stdout文件描述符。

The following are the built in macros defined in the unistd.h header file. 以下是unistd.h头文件中定义的内置宏。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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