我想从文件中读取特定行,并且可以获取行号,但我不知道如何去做,这是迄今为止:C - 从文件中读取特定行
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *file;
file = fopen("temp.txt","r");
char tmp[256]={0x0};
char *tmpline;
int numline = 1;
while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
{
tmpline = strstr(tmp,"status:green");
if(tmpline) {
printf("%d - %s", numline, tmpline);
}
numline++;
}
if (file != NULL) fclose(file);
return 0;
}
测试文件看起来像:
s1.server.com
127.0.0.1
status:green
s2.server.com
127.0.0.1
status:red
s3.server.com
127.0.0.1
status:red
s4.server.com
127.0.0.1
status:green
的输出,我是:
3 - status:green
15 - status:green
但我真的想表明的是:
s1.server.com
s4.server.com
我希望它搜索“状态:绿色”再回去了几行,以显示它属于
为什么要重新发明轮子?这可以通过一个awk单行程来解决 - 例如'awk
tdammers
2011-04-12 14:32:03
@tdammers,不完全是这样:zoite想要在他看到时显示一个*更早的*行“状态:绿色”。你仍然可以通过简单的awk调用来实现,但并不那么容易。 – 2011-04-12 14:36:38
这可能是如此,但他问如何在C. – James 2011-04-12 14:39:33