我想问你,如何使用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;
}
答案 0 :(得分:0)
您可以使用freopen()
使stdin
引用输入文件而不是键盘。
这可以用于输入或输出重定向。
在您的情况下,请执行
freopen("file.txt", "r", stdin);
现在stdin
与文件file.txt
相关联,当您使用scanf()
等函数阅读时,您实际上正在阅读file.txt
。
freopen()
将关闭旧流(此处为stdin
)&#34;否则,该函数的行为与fopen()
&#34;类似。如果发生某些错误,它将返回NULL
。因此,您最好检查freopen()
返回的值。
正如其他人所指出的那样,你发布它的代码可能有一个无限循环,因为input
的值永远不会在循环内发生变化。
答案 1 :(得分:0)
将建议的代码编译/链接到某个文件中,让我们调用该可执行文件: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