Line number and position from absolute file position

April 24, 2008

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 

void usage()
{
	printf("file_pos  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 < 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;
}

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!

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment