c - 需要帮助在 C 中使用函数实现 kittycat 函数
问题描述
需要帮助获取 display_stream 函数以从 Shell 中的标准输入读取。当我在 Shell 中键入“./kittycat”时,当它应该从标准输入中读取时,我变得空白。其他一切都适用于一个或多个参数,它读取文本文件(./kittycat test.txt test2.txt),如果我输入'./kittycat error.txt',它会说找不到错误文件。我只是缺少一种使用函数 display_stream 从标准输入读取的方法。包括 shell 输出与预期的截图。
[enter image description here][1]#include <stdio.h>
#include <stdlib.h>
void display_stream(FILE *fptr);
int
main(int argc, char *argv[])
{
int i;
// if no args given, read from stdin (just like shell/cat)
if (argc < 2)
display_stream(stdin);
for (i = 1; i < argc; i++) {
FILE *fptr = fopen(argv[i], "r");
if (fptr == 0) {
printf("error: file not found.");
continue;
}
display_stream(fptr);
fclose(fptr);
}
return 0;
}
void
display_stream(FILE *fptr)
{
int x;
/* read one character at a time from file, stopping at EOF,
which indicates the end of the file. */
while ((x = fgetc(fptr)) != EOF)
putchar(x);
}
解决方案
- 搬出
fclose
去display_stream
,它不属于那里。将其放置在对 的调用之后display_stream
。 - 在循环之前或之后添加
display_stream(stdin)
到main
(没有fclose
这个时间,stdin
不应该关闭)。它应该可以工作。
它可能会逐行从标准输入复制,但这是由于程序外部的缓冲而禁用 AFAIK 并不容易。
另外,printf( "%c", x )
可能是putchar(x)
推荐阅读
- java - Hibernate:@OrderColumn,添加删除重新插入
- apache-spark - 查询需要很长时间'选择'什么
- java - 如何确定各种 Java 8 堆内存名称?
- jquery - 在jQuery中获取TD单元格的值
- php - 在具有特定类的 div 中获取 preg_match_all 锚文本
- python - 在 Pandas 中创建淘汰赛比赛
- python-3.x - 如何捕捉错误(Smartsheet API Python SDK)
- python-3.x - 在使用多个输入层训练的 keras 模型中,如何在预测时忽略某些输入层?
- java - Android studio gradle .pom 文件下载错误
- c# - C#删除错误文件