如何在 C 中使用重定向进行文件输入 [英] How to use redirection in C for file input

查看:24
本文介绍了如何在 C 中使用重定向进行文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

./a.out < fileName.txt

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

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

推荐答案

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

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)

#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;
}

这篇关于如何在 C 中使用重定向进行文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆