【发布时间】:2021-11-04 16:45:28
【问题描述】:
需要帮助获取 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);
}
【问题讨论】:
-
我觉得没问题。你有什么问题?
-
显示标准输入和文件中的文本 你应该向用户询问一些文本吗?那部分不清楚。
-
你需要在
display_stream(fptr)之后调用fclose(fptr) -
"r\n"?? open-mode argument 中的换行符在做什么? -
试试
fopen( argv[i], "r\n" )-->fopen( argv[i], "r" )