how to look for a string on a file and get its line number
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.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;
}
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.
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.
精彩评论