【问题标题】:Reading contet from stdin file using <file.txt in C, fopen is forbidden在 C 中使用 <file.txt 从标准输入文件中读取内容,禁止使用 fopen
【发布时间】:2018-03-27 03:23:02
【问题描述】:

我想问你,如何用 C 语言读取文件:

your_program <file.txt

cat file.txt
Line one
Line two
Line three

我有类似的东西,但它不起作用。非常感谢

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int vstup;
    input = getchar();


    while( input != '\n')
        printf("End of line!\n");
    return 0;
}

【问题讨论】:

  • 您希望程序的输出是什么?实际输出是多少?你意识到你做了一个无限循环,因为input 在你第一次分配之后就永远不会改变,对吧?
  • 这怎么行不通?
  • 您只从文件中读取了一个字符。
  • 您也可能想阅读以下内容:How to debug small programs

标签: c stdin


【解决方案1】:

将建议的代码编译/链接到某个文件中,让我们调用该可执行文件:run

在运行以下建议的代码时,从输入文件重定向“stdin”

./run < file.txt

这是建议的代码:

                     // <<-- document why a header is being included
#include <stdio.h>   // getchar(), EOF, printf()
//#include <stdlib.h>  <<-- don't include header files those contents are not used

int main( void )    // <<-- since the 'main()' parameters are not used, 
                    //      use this signature
{
    int input;      // <<-- 'getchar()' returns an integer and EOF is an integer
    while( (input = getchar() ) != EOF ) // <<-- input one char per loop until EOF
    {
        if( '\n' == input )              // is that char a newline?
        {
            printf("End of line!\n");    // yes, then print message
        }
    }
    return 0;
} // end function: main   <<-- document key items in your code

【讨论】:

    【解决方案2】:

    您可以使用freopen() 使stdin 引用输入文件而不是键盘。

    这可用于输入或输出重定向。

    在你的情况下,做

    freopen("file.txt", "r", stdin);
    

    现在stdin 与文件file.txt 相关联,当您使用scanf() 之类的函数读取时,您实际上是从file.txt 读取。

    freopen() 将关闭旧流(此处为stdin)“否则,该函数的行为就像fopen()”。如果发生错误,它将返回NULL。所以你最好检查freopen()返回的值。

    阅读更多关于freopen()herehere的信息。

    正如其他人指出的那样,您发布的代码可能存在无限循环,因为 input 的值在循环内永远不会改变。

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      相关资源
      最近更新 更多