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);
}

Initialize 2D Array

Three different ways to initialize a 2D array

char array[N][M];
and you want to initialize each member of that array to some character

//method 1, two loops
for(i=0;i < N;i++)
{

for(j=0;j < M;j++ )
{

a[i][j]='c';
}
}


//method2, one loop
char *p=a;
for(i=0;i < N*M;i++)
{

p[i]='d';
}


//method3, one line
memset(a,'e',N*M);

Wednesday, April 16, 2008

Convert Integer to String

Program convert an integer to string
/****
function that converts an integer into a string
representing of that integer....
[integer can start with an optional + or - sign]

intTOstring1() - uses while loop (need reverse() to
reverse the string

intTOstring2() - uses recursion ( don't need to reverse )

example
char s[100];
intTOstring(-134234, s);
printf(s);
output: -134234
****/

//This function uses recursion to convert integer to string
void intTOstring2(int x, char *s)
{

static int i = 0;
if (x < 0)
{

s[i++] = '-';
x = -x;
}
if ( x/10 )
{

intTOstring2( x/10, s );
}
s[i++] = x%10 + '0';
s[i] = '\0';
}

//This function uses a while loop to convert integer to string
//This function will then call reverse() function to reverse the string
void intTOstring1(int x, char *s)
{

int isNegative = 0,tmp;
char *p = s,*t = s,tmp1;
if( x == 0 )
{

*s = '0';
*(s+1) = '\0';
return;
}

if ( x < 0 )
{

isNegative=1;
x*=-1;
}

//keep dividing by 10 and collect each digit
while ( x > 0 )
{

tmp = x%10;
*p++ = tmp+'0';
x /= 10;
}
if( isNegative )
*p++ = '-';
*p = '\0';
}

//reverse the string
void reverse( char *s )
{

char *p = s,*t = s,tmp;

while ( *p )
p++;
while ( t < p )
{

tmp = *t;
*t++ = *--p;
*p = tmp;
}
}

First Post

Welcome

Here you will find some of the problems I face during my work and how I fixed it
Enjoy!!!

Srithar