How to fgets() a specific line from a file in C?

眉间皱痕 提交于 2019-11-27 09:32:11

Unless you know something more about the file, you can't access specific lines at random. New lines are delimited by the presence of line end characters and they can, in general, occur anywhere. Text files do not come with a map or index that would allow you to skip to the nth line.

If you knew that, say, every line in the file was the same length, then you could use random access to jump to a particular line. Without extra knowledge of this sort you simply have no choice but to iterate through the entire file until you reach your desired line.

If you know the length of each line, you can use fseek to skip to the line you want.

Otherwise, you need to go through all lines.

Keith Thompson

First off, your line

buffer =(char*)malloc(sizeof(char) * strlen(line));

is better written as:

buffer = malloc(strlen(line) + 1);

The + 1 is needed to provide room for the terminating '\0' character; strlen() doesn't account for that. Casting the result of malloc() in C is not necessary, and in some cases can mask errors. sizeof(char) is 1 by definition, so that's not needed.

And you never change the value of targetline, so your loop will never terminate.

But in answer to your question, if you have a text file and you want to read the Nth line of it, you have to read and skip the first N-1 lines to get to it. (It's possible to set up a separate index, but creating the index requires reading through the file anyway, and keeping the index current as the file changes is a difficult problem, probably beyond what you're doing now. And it's not particularly necessary; the time to read 10 lines from a file won't be noticeable.)

I'm afraid, there is no other way to get nth line in the file. You have to go through. There is no random acces within the file.

If you want to get the nth line from a text file, you have to read the n-1 lines before it. That's the nature of a sequential file. Unless you know that all of your lines are the same length, there's no way to reliably position to the start of a particular line.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!