i new c, , trying build c program scans through file until eof, picks out lines contain keyword , sets offset after last line searched. when scan executed again, scans file, time starting saved offset , continues downward until eof.
i trying wrap head around different functions of file i/o , i'm having trouble piecing procedure call fopen(), fseek(), fgets(), ftell(), etc want do. can point me in right direction or walk me through need done?
thank you!
i recomment using getline reading, , ftell , fseek getting/setting offset (and strstr searching individual lines) in case.
i'm not sure understand saving of offset about, might this:
int pick_lines(const char *filename, const char *keyword, long *offset) { file *fp; char *line = null; size_t len = 0; if (offset == null || (fp = fopen(filename, "r")) == null) return 1; if (*offset > 0 && fseek(fp, *offset, seek_set) != 0) { fclose(fp); return 1; } while (getline(&line, &len, fp) != -1) { if (strstr(line, keyword) != null) printf("%s", line); // or else chosen line } if ((*offset = ftell(fp)) < 0) { free(line); fclose(fp); return 1; } free(line); fclose(fp); return 0; } here offset in/out parameter. it's dereferenced value used seek given offset (start *offset == 0) , reset new offset.
this function print every line contains keyword. if want return array of lines instead, little work needed.
an example of usage might be:
long offset = 0; pick_lines(filename, keyword, &offset); // append lines file pick_lines(filename, keyword, &offset); // ...
Comments
Post a Comment