c - 如何在C中读取通过stdin传递的文件
问题描述
我想将一个文本文件传递给这样的 C 程序./program < text.txt
。我在 SO 上发现这样传递的参数不会出现argv[]
在stdin
. 如何在标准输入中打开文件并阅读它?
解决方案
您可以直接读取数据而无需打开文件。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
。
推荐阅读
- javascript - 如何处理 30'000 个 url 的文件而不发生内存泄漏?
- kotlin - 等于两个对象开放类
- mysql - 从 mysqlc 获取的 json 生成报告
- python - pandas:groupby sum 以其他列为条件
- php - PHP 或 Laravel 中的 Amazon Transcribe 流媒体服务请求?
- git - 为什么 git pull autostash 需要变基?
- database - Prisma:所有迁移都已应用
- python - 在 Python 中制作浓度列表时遇到问题
- oracle - 如何在卡片模板中添加图像而不是图标 - Oracle Apex
- reactjs - ReactJS,Mobx:如何强制完成单个组件的类似刷新的重新加载?