获取日志的倒数某行或者几行

输出文本或者日志的倒数第3行:
cat 1.txt | tac | sed -n '3p'
tail -3 1.txt | head -1

C程序示例:读取加载到链表再遍历出指定行

#include
#include
#include

#define N 3

typedef struct Tread{
	char str[200];
	struct Tread * next;
}tread ,*Linklist;


tread * createlist();
int length();
char * find();

tread * createlist(tread * head){
	tread *p1,*p2;
	FILE *fp;fp=NULL;
	char test[200];memset(test,200,0);
	fp=fopen("1.txt","rb");
	if(!fp) return NULL;
	p1=p2=(tread *)malloc(sizeof(tread));
	if(p1==NULL|| p2 ==NULL){
		printf("MALLOC ERROR!\n");
		return NULL;
	}
	strcpy(p1->str,"start!");
	//printf("%s\n",p1->str);
	p1->next=NULL;
	while(strlen(p1->str)>0){
		if(head==NULL){ 
			head=p1;p2=head;
		}else{
			p2->next=p1;
			p2=p1;
		}
		/*if(!feof(fp)){
			p1=(tread *)malloc(sizeof(tread));
            fgets(test,200,fp);
	        strcpy(p1->str,test);
			printf("%s",p1->str);
			printf("%p\n",fp->_IO_read_ptr);
		}else{
			break;
		}*///windows平台可以,Linux平台会多输出一行。
		if(fgets(test,200,fp)!=NULL){
			p1=(tread *)malloc(sizeof(tread));
            strcpy(p1->str,test);
			//printf("%s",p1->str);
			//printf("%p\n",fp->_IO_read_ptr);
			
		}else{
			break;
		}
	}
	free(p1);p1=NULL;
    p2->next=NULL;
	fclose(fp);
    return head;	
}

int length(tread *head){
	int lonng=0;
	if(head==NULL) return 0;
	while(head !=NULL){
		lonng++;
		head=head->next;
	}
	return lonng;
}

char * find(tread *head,int LEN,char *STR){
	int i=0;
	if(head ==NULL) return NULL;
	while(head!=NULL){
		i++;
		if(i==LEN){
			strcpy(STR,head->str);
			break;
		}
		head=head->next;
	}
	return STR ;
}

int main(int argc,char *argv[]){
	Linklist Thead =NULL;
	char str1[200];
	memset(str1,200,0);
	Thead = createlist(Thead);
	int len =length(Thead);
	find(Thead,len-N+1,str1);
	printf("len=%d,str1=%s",len,str1);
	return 0;
}

 

你可能感兴趣的:(Linux-杂碎)