如何在C中读取通过stdin传递的文件 [英] How to read a file passed through stdin in C

查看:37
本文介绍了如何在C中读取通过stdin传递的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文本文件传递给这样的 C 程序 ./program <;文本.txt.我在 SO 上发现这样传递的参数不会出现在 argv[] 中,而是出现在 stdin 中.如何在标准输入中打开文件并读取它?

I want to pass a text file to a C program like this ./program < text.txt. I found out on SO that arguments passed like that dont appear in argv[] but rather in stdin. How can I open the file in stdin and read it?

推荐答案

可以直接读取数据,无需打开文件.stdin 已经打开.如果没有特殊检查,您的程序不知道它是文件还是来自终端或管道的输入.

You can directly read the data without having to open the file. stdin is already open. Without special checks your program doesn't know if it is a file or input from a terminal or from a pipe.

您可以使用 read 或使用 stdio.h 中的函数通过其文件描述符 0 访问 stdin.如果该函数需要 FILE *,您可以使用全局 stdin.

You can access stdin by its file descriptor 0 using read or use functions from stdio.h. If the function requires a FILE * you can use the global stdin.

示例:

#include <stdio.h>
#define BUFFERSIZE (100) /* choose whatever size is necessary */

/* This code snippet should be in a function */

char buffer[BUFFERSIZE];

if( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
    /* check and process data */
}
else
{
    /* handle EOF or error */
}

您也可以使用 scanf 来读取和转换输入数据.此函数总是从 stdin 读取(与 fscanf 相反).

You could also use scanf to read and convert the input data. This function always reads from stdin (in contrast to fscanf).

这篇关于如何在C中读取通过stdin传递的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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