阅读contet,FOPEN禁止

问题描述:

我想问问你,如何从文件中使用C语言阅读:阅读contet,FOPEN禁止

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; 
} 
+0

您希望从程序中获得什么输出?实际产出是多少?你意识到你做了一个无限循环,因为'input'在你第一次分配给它之后永远不会改变,对吧? –

+1

以及这不工作? –

+0

您只读取了文件中的一个字符。 –

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

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

在你的情况,做

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

现在stdin与文件相关file.txt,当你阅读使用像scanf()功能,你实际上是从file.txt阅读。

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

查看更多about freopen()herehere

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

编译/中提出的代码链接到一些文件,让调用可执行文件:run

运行下面的建议代码时,输​​入文件

./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