[hadoop@iZ25s7cmfyrZ C_script]$ cat jansson_and_dir.c
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <jansson.h>
#include <iconv.h>
void print(char *str)
{
printf("%s\n",str);
}
int get_line_max(FILE *ptr)
{
int i=0,max=0;
char c;
while(!feof(ptr))
{
c=fgetc(ptr);
i=1;
while(c!='\n' && c!=EOF)
{
c=fgetc(ptr);
i++;
}
if (max<i) max=i;
}
return i;
}
int gbk_to_utf8(char *sour, size_t inlen,char *dst,size_t outlen)
{
iconv_t cd;
//int inlen=strlen(sour);
//int outlen=inlen*3;
char **inbuf=&sour;
char **outbuf=&dst;
cd=iconv_open("utf-8","gb18030");
if(cd==0)
return -1;
memset(dst,0,outlen);
if(iconv(cd,inbuf,&inlen,outbuf,&outlen)==-1)
return -1;
iconv_close(cd);
return 0;
}
void json_to_line(char *text)
{
json_t *data;
json_error_t error;
data=json_loads(text,0,&error);
if(data)
{
//print(json_dumps(json_object_get(data,"companyInfo"),0));
data=json_array_get(json_object_get(data,"companyInfo"),0);
//printf("%d\n",json_is_object(json_loads(json_dumps(data,0),0,NULL)));
}
}
int main()
{
char path[]="/data/yunke/source/company/spider_20160919/";
DIR *dirptr;
struct dirent *entry;
system("clear");
if((dirptr=opendir(path))==NULL)
{
fprintf(stderr,"PATH ERROR!!\n");
return 1;
}
else
{
while(entry=readdir(dirptr))
{
if(entry->d_name[0]!='.')
{
char *file;
FILE *fptr;
int max;
char *temp;
char *line;
size_t inlen;
size_t outlen;
int t;
file=malloc(sizeof(path)+sizeof(entry->d_name));
strcpy(file,path);
strcat(file,entry->d_name);
//print(file);
if((fptr=fopen(file,"r"))==NULL)
{
print("FILE read error!!\n");
}
else
{
max=get_line_max(fptr);
//printf("%d\n",max);
temp=malloc(max);
line=malloc(max*3);
rewind(fptr);
inlen=max;
outlen=max*3;
while(!feof(fptr))
{
fgets(temp,max,fptr);
t=gbk_to_utf8(temp,inlen,line,outlen);
//print(line);
json_to_line(line);
printf("%d\n",t);
}
free(temp);
free(line);
}
free(file);
fclose(fptr);
}
}
closedir(dirptr);
}
return 1;
}