【问题标题】:How to read a file passed through stdin in C如何在C中读取通过stdin传递的文件
【发布时间】:2019-03-13 13:34:21
【问题描述】:

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

【问题讨论】:

  • @LiranFunaro - 他们要求 C - 你的链接是关于 C++ 的。 C 不做cincout。对于 C,请尝试阅读类似本教程的内容(我不知道它有多好 - 但如果不是您需要的,您当然可以谷歌其他人如何使用 stdin)。 cs.bu.edu/teaching/c/file-io/intro
  • 你已经打开了这个文件,#inlude <stdio.h>fread(buff, size, 1, stdin);
  • 你没有打开任何东西(你的shell做了输入重定向),你只是从stdin读取通常的方式-fgets()getchar()scanf(),不管.
  • 文件未“通过标准输入”。文件标准输入。

标签: c stdin


【解决方案1】:

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

您可以使用read 通过其文件描述符0 访问stdin 或使用stdio.h 中的函数。如果函数需要FILE *,您可以使用全局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 不同)。

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多