|
まあこんな物でしょうか。
当然一行目に発見された場合は何も表示せずに終了します。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *fp;
long ft;
char buf[128], *str = "ewc"; /* 検索する文字列 */
int i;
if ((fp = fopen("name.dat", "r")) == NULL) exit(1);
while (1) {
fgets(buf, 128, fp);
if (feof(fp)) goto end;
ft = ftell(fp);
if (strstr(buf, str)) break;
}
fseek(fp, ft, SEEK_SET);
while (1) {
if (fseek(fp, --ft, SEEK_SET)) goto end;
i = fgetc(fp);
if (i == '\n') break;
}
fseek(fp, --ft, SEEK_SET);
while (1) {
if (fseek(fp, --ft, SEEK_SET)) goto end;
i = fgetc(fp);
if (i == '\n') break;
}
fseek(fp, --ft, SEEK_SET);
while (1) {
if (fseek(fp, --ft, SEEK_SET)) {
fseek(fp, ++ft, SEEK_SET);
break;
}
i = fgetc(fp);
if (i == '\n') break;
}
fgets(buf, 128, fp);
printf("一行前の行 = %s", buf);
end:
return 0;
}
|