首页 > 解决方案 > 如何在C中读取通过stdin传递的文件

问题描述

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

标签: cstdin

解决方案


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

您可以stdin通过其文件描述符0使用read或使用来自stdio.h. 如果函数需要 aFILE *您可以使用全局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


推荐阅读