Search code examples
cfileiolines

Is there a way to find the line number of the current line being read from a file?


1) Is there a way in C that we could find the line number of a line that we are reading from a file.

2) I would also like to know if there is another way to find out the total number of lines in a file other than by creating a loop which looks for EOF in each line until it reaches the end.


Solution

  • 1)Is there a way in C that we could find the line number of a line that we are reading from a file.

    Not unless you count the lines from the beginning of the file. You can't just position yourself arbitrarily in a file and know what line of text you're on, unless there is information in the file itself telling you, or you have created an index of sorts by a previous pass over the file. The usual approach is to accumulate a line count as you process lines from the file.

    2)I would also like to know if there is another way to find out the total number of lines in a file other than by creating a loop which looks for EOF in each line until it reaches the end.

    No. You must run through the whole the file and count the number of lines. Any external tools (such as wc) are doing exactly this. You need to be aware of different line-ending styles. Depending on what functions you are using to read the file, you may or may not have automatic newline translation.