str_tok函数

#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <signal.h>
#include <dirent.h>


int  read_file(char **data_buf,int *data_len)
{
    int ret,size;
    char *p;
    FILE *fp = NULL;
        fp = fopen("./file.log","rb");  
        if(NULL == fp){  
            return -1;  
        } 
        //求得文件的大小  
        fseek(fp, 0, SEEK_END);  
        size = ftell(fp);  
        rewind(fp);  
        //申请一块能装下整个文件的空间  
        p = (char*)malloc(sizeof(char)*size);  
        if(p==NULL){
            fclose(fp);
            return -1; 
        }
		memset(p,0,sizeof(char)*size);
        //读文件  
        fread(p,1,size,fp);//每次读一个,共读size次  
      
        *data_buf=p;
        *data_len=size;
        fclose(fp);  
        return 0;
}

char * str_tok( char * src,const char c ,char ** turn )
{
	char * s=src, * head_str=s, * p, * p_c ;
	int len;
	if( src==NULL ) return NULL;
 	
	if ( *s != '\0' &&  strlen(s) != 0 ){
		
            p_c=strchr(s,c);
			len=abs( p_c - head_str ); //如果需要处理被查找字符 需要  +sizeof(char)
			if (p_c!=NULL){
				p = (char*)malloc(sizeof(char)*len+sizeof(char));  
				if(p==NULL){
				return NULL; 
				}
				memset(p,0,sizeof(char)*len+sizeof(char));
				*turn=p_c+1;
				memcpy(p,head_str,len);
				return p;
			}else{
				return NULL;
			}	
		
	}
	return NULL;	
}

int  main()
{
	char *pcont;
	int lenth;
	char * res;
	char *P_turn;
	read_file(&pcont,&lenth);
	P_turn=pcont;
	while( ( res = str_tok(P_turn, '\n',&P_turn) ) != NULL ){
		printf("res=%s\n",res);
		free(res);
		res=NULL;
		sleep(1);
	}
	free(pcont);
	pcont=NULL;
	return 0;
}
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值