How to find the current line position of file pointer in C?
Asked Answered
L

3

12

How can I get the current line position of the file pointer?

Lituus answered 28/3, 2010 at 15:40 Comment(0)
E
16

There is no function that gives you current line. But you can use ftell function to get the offset in terms of number of char from the start of the file.

Everglades answered 28/3, 2010 at 15:42 Comment(3)
Not the number of characters. The number of bytes. C mashes together the concepts, sure, but they are different.Ligamentous
@Donal: He said 'char', which is how C spells 'byte'.Giorgi
Careful. ftell might not return something directly meaningful for a text-mode stream.Mushroom
L
5

There is no function to get the current line; you'll have to keep track of it yourself. Something like this:

FILE *file;
int c, line;

file = fopen("myfile.txt", "rt");
line = 0; /* 1 if you want to call the first line number 1 */
while ((c = fgetc(file)) != EOF) {
    if (c == '\n')
        ++line;
    /*
        ... do stuff ...
    */
}
Loathsome answered 28/3, 2010 at 15:49 Comment(0)
H
4

You need to use ftell to give you the position within the file.

If you want the current line, you'll have to count the number of line terminator sequences between the start of the file and the position. The best way to do that is to probably start at the beginnning of the file and simmply read forward until you get to the position, counting the line terminator sequences as you go.

If you want the current line position (I assume you mean which character of the current line you're at), you'll have to count the number of characters between the line terminator sequence immediately preceding the position, and the position itself.

The best way to do that (since reading backwards is not as convenient) is to use fseek to back up a chunk at a time from the position, read the chunk into a buffer, then find the last line terminator sequence in the chunk, calculating the difference between that point and the position.

Harriott answered 28/3, 2010 at 15:49 Comment(1)
The 'best way' assumes you have a seekable device, rather than, say, a terminal or pipe as the input. It also assumes you are dealing with a readable file pointer - there is a 'current line position' in output streams too.Blinker

© 2022 - 2024 — McMap. All rights reserved.