[英]How to read in a specific line from an input file in C?
If I want to read in a specific line without knowing what exactly is in that line how would I do that using fscanf? 如果我想在特定行中阅读而又不知道该行到底是什么,我将如何使用fscanf来做到这一点?
one \n
two \n
three \n
i want this line number four \n
five \n
six \n
How would I read in the 5th line in that input text file? 我将如何阅读该输入文本文件的第五行? Do I need to use a while loop or a for loop?
我需要使用while循环还是for循环?
You can use any loop both work more or less same way 您可以使用任何循环或多或少以相同的方式工作
Here is something you can do 这是你可以做的
int ch, newlines = 0;
while ((ch = getc(fp)) != EOF) {
if (ch == '\n') {
newlines++;
if (newlines == 5)
break;
}
}
Or you can use fgets because fgets places the "\\n" (newline) at the end of the line 或者您可以使用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.