首页 > 解决方案 > 需要帮助在 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);
    }

我的输出 预期结果

标签: cfile-io

解决方案


  1. 搬出fclosedisplay_stream,它不属于那里。将其放置在对 的调用之后display_stream
  2. 在循环之前或之后添加display_stream(stdin)main(没有fclose这个时间,stdin不应该关闭)。它应该可以工作。

它可能会逐行从标准输入复制,但这是由于程序外部的缓冲而禁用 AFAIK 并不容易。

另外,printf( "%c", x )可能是putchar(x)


推荐阅读