Skip to content

Instantly share code, notes, and snippets.

@lindenb
Created July 28, 2010 21:10
Show Gist options
  • Save lindenb/496309 to your computer and use it in GitHub Desktop.
Save lindenb/496309 to your computer and use it in GitHub Desktop.
%{
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#define MIN(a,b) (a<b?a:b)
static char* title=NULL;
static char* buffer=NULL;
static unsigned long fragment_size=0L;
static unsigned long buffer_size=0;
static int sequence_index=0;
static void overflow()
{
++sequence_index;
fprintf(stdout,"%s_%05d\n",title,sequence_index);
fwrite(buffer,sizeof(char),buffer_size,stdout);
fputc('\n',stdout);
buffer_size=0;
}
%}
%option never-interactive
%option noyywrap
%%
^>.*\n {
if(buffer_size>0) overflow();
title=realloc(title,sizeof(char)*yyleng);
if(title==NULL)
{
fprintf(stderr,"Out of memory\n");
exit(EXIT_FAILURE);
}
strncpy(title,yytext,yyleng-1);
sequence_index=0;
}
^[A-Za-z]+ {
int nCopy=0;
while(nCopy!=yyleng)
{
int len=MIN(fragment_size - buffer_size,yyleng-nCopy);
memcpy(&buffer[buffer_size],&yytext[nCopy],len);
buffer_size+=len;
nCopy+=len;
if(buffer_size==fragment_size)
{
overflow();
}
}
}
[ \t\n] ;
. {
fprintf(stderr,"Illegal character \"%s\".", yytext);
exit(EXIT_FAILURE);
}
<<EOF>> {
if(buffer_size >0) overflow();
free(title);
title=NULL;
buffer_size=0;
return 0;
}
%%
int main(int argc,char** argv)
{
int optind=1;
while(optind<argc)
{
if(strcmp(argv[optind],"-h")==0)
{
fprintf(stderr,"Options:");
fprintf(stderr," -n <int> chunk size");
return EXIT_SUCCESS;
}
else if(strcmp(argv[optind],"-n")==0)
{
fragment_size=atol(argv[++optind]);
}
else if(strcmp(argv[optind],"--")==0)
{
++optind;
break;
}
else if(argv[optind][0]=='-')
{
fprintf(stderr,"bad options \"%s\".\n",argv[optind]);
return EXIT_FAILURE;
}
else
{
break;
}
++optind;
}
if(fragment_size<=0UL)
{
fprintf(stderr,"bad size: %ld\n",fragment_size);
exit(EXIT_FAILURE);
}
buffer=malloc(sizeof(char)*fragment_size);
if(buffer==NULL)
{
fprintf(stderr,"Out of memory\n");
exit(EXIT_FAILURE);
}
if(optind==argc)
{
yylex();
}
else
{
while(optind< argc)
{
char* filename=argv[optind++];
errno=0;
yyin=fopen(filename,"r");
if(yyin==NULL)
{
fprintf(stderr,"Cannot open %s. %s\n",filename,strerror(errno));
exit(EXIT_FAILURE);
}
yylex();
fclose(yyin);
}
}
free(buffer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment