C语言 如何在 C 中使用重定向进行文件输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19467865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:45:48  来源:igfitidea点击:

How to use redirection in C for file input

cinputio-redirection

提问by Dexter

I need to get the file from the terminal, I know the command will look like:

我需要从终端获取文件,我知道命令看起来像:

./a.out < fileName.txt

I'm not sure how to use fgets() in my program to use the file requested from the terminal.

我不确定如何在我的程序中使用 fgets() 来使用从终端请求的文件。

回答by Nigel Harper

Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)

使用重定向将输入文件的内容发送到 stdin,因此您需要从代码中的 stdin 读取,例如(为清楚起见省略了错误检查)

#include <stdio.h>

#define BUFFERSIZE 100

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    fgets(buffer, BUFFERSIZE , stdin);
    printf("Read: %s", buffer);
    return 0;
}

回答by Pratik

1.) you close stdin then assign a different file handler to it 2.) replace stdin with any other file handler using dup2 function you can achieve it

1.) 您关闭 stdin 然后为其分配不同的文件处理程序 2.) 使用 dup2 函数将 stdin 替换为您可以实现的任何其他文件处理程序