tags:

views:

51

answers:

3

Good day all,

I need you guys assistance on this problem I can't figure out how to go around this at the moment. I have a file that contains dates in the format below.
03\03\2010

04\03\2010

05\03\2010

06\03\2010

07\03\2010

08\03\2010

09\03\2010

10\03\2010
. . .
. . .
. . .
I want to get the line number of any specified date string from the file. That is if I want to get the line number of 09\03\2010 how can I achieve this.

A: 

As you parse the text file sequentially, increment a counter every time you encounter a \n character. This will be your 0-based line number counter.

tenfour
A: 

Unless you are doing this for homework or sport, use existing tools instead. On Unix, that would be fgrep in this case.

If you must reimplement, code up a state machine, incrementing a line counter in response to the state transition caused by reading a newline.

Vebjorn Ljosa
+2  A: 

Read the file a line at a time (e.g., with fgets), counting the iterations until you reach a line that matches.

#define max_len 256

char line[max_len];
int current_line = 0;

while (fgets(file, line, sizeof(line))) {
    ++current_line;
    if (0 == strcmp(line, target))
        return current_line;
}
Jerry Coffin