我想從文件中讀取特定行,並且可以獲取行號,但我不知道如何去做,這是迄今爲止: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