Thursday, April 17, 2008

Add blockquote to a c file

#include"stdio.h"
#include"stdlib.h"

/****
Read in a file as input file.c
whenever you encounter '{', replace it with '{blockquote_begin'
whenever you encounter '}', replace it with 'blockquote_end}'
write output to file file.c.blog
****/

int main(int argc, char ** argv)
{

char *fout;
FILE *in, *out;
int len,c;
if ( argc == 2 )
{

in = fopen(argv[1],"r");
if(in==NULL)
{

printf("open file %s failed!\n",argv[1]);
return 1;
}
len=strlen(argv[1])+1+5;
fout=malloc(sizeof(*fout)*(len+1+5));
strcpy(fout,argv[1]);
strcat(fout,".blog");
out = fopen(fout,"w");
if(out==NULL)
{

printf("open file %s failed!\n",fout);
return 1;
}
printf ("in %s\nout %s\n",argv[1],fout);
}
else
{

printf("Usage: \n");
printf("%s \n",argv[0]);
return 2;
}

do
{

c=fgetc(in);
if( c == '{')
{

fprintf(out,"%c%s",'{',"blockquote_begin");
}
else if (c == '}')
{

fprintf(out,"%s,%c","blockquote_end",'}');
}
else if (c != EOF)
{

fputc(c,out);
}
}while (c!=EOF);
fclose(in);
fclose(out);
free(fout);
}

6 comments:

KBS said...

WHy do u do that man?
Print each character separately?

sridotc said...

I see it

fputs

I also need to return whenever "file does not exist"

I will make those two changes tonight

thanks

sridotc said...

I also need to free the memory

fout=malloc(sizeof(*fout)*(len+1+5));

so 3 items need to be fixed

KBS said...

not just fputs

u can use fprintf

or at least you could have created ur own output routine that looped through a string and used fputc or putc

sridotc said...

yeap fixed all three issues

yea I should just use fprintf, then just one line

anyways I wonder why I did not think that

cuz I thought fputc / fputs are cooler

srithar

sridotc said...

I updated this program as well.
Its more compact, easy to read, and also more efficient.