[英]How to read in a specific line from an input file in C?
如果我想在特定行中阅读而又不知道该行到底是什么,我将如何使用fscanf来做到这一点?
one \n
two \n
three \n
i want this line number four \n
five \n
six \n
我将如何阅读该输入文本文件的第五行? 我需要使用while循环还是for循环?
您可以使用任何循环或多或少以相同的方式工作
这是你可以做的
int ch, newlines = 0;
while ((ch = getc(fp)) != EOF) {
if (ch == '\n') {
newlines++;
if (newlines == 5)
break;
}
}
或者您可以使用fgets,因为fgets将“ \\ n”(换行符)放在行尾
char line[100]; int newline=0;
while ( fgets( line, 100, stdin ) != null )
{
newline++;
if(newline==5)
{
fprintf("The line is: %s\n", line);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.