coderholic

Line number and position from absolute file position

I was once having some issues with a compiler because when it found errors rather than giving me the line number and character position of the error it would report the file position. It was a real nightmare trying to work out where the errors actually were, because my text editor only told me the line number and line position of the current character, not the overall file position.

My solution was to write the following small C program, which given a position and a filename outputs a line number and line position.

#include <stdio.h>

void usage()
{
    printf("file_pos <character> <filename>n");
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage();
        return 0;
    }

    // open a file
    char *filename = argv[2];
    FILE *fp = fopen(filename, "r");

    // seek to given position
    int position = atoi(argv[1]);
    int lineNumber = 0;
    int linePosition = 0;
    char ch;
    int i;
    for(i = 0; i &lt; position; i++)
    {
        ch = fgetc(fp);
        if(ch == 'n')
        {
            lineNumber++;
            linePosition = 0;
        }
        else
        {
            linePosition++;
        }
    }

    printf("Position %d is line %d and character %dn", position, lineNumber, linePosition);
    return 0;
}
</filename></character></stdio.h>

And here it is in action:

~$ ./file_pos 50 file_pos.c
Position 50 is line 4 and character 15

Fortunately compilers are much more friendly these days!

Posted on 24 Apr 2008
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.