The following code can detect a (single) macro name (stored in str1) from a file and store its definition (stored in str2) and then reads the file again to write into a new file, replacing all occurrences of the macro name with its definition. The code when executed gives segmentation fault, please help me remove it. the mac() is working properly, there's a problem with the main(). Please help.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *fp1, *fp2;
int i;
char str[10];
char str1[10],str2[10];
void mac (void) {
char ch;
fp1=fopen("comm.txt","r");
do{
ch=fgetc(fp1);
if(ch!='\n')
{
while(ch!='\n')
{
ch=fgetc(fp1);
}
}
ch=fgetc(fp1);
if (ch=='#')
{
ch=fgetc(fp1);
if(ch==' ')
{
i=0;
ch=fgetc(fp1);
while (ch!=' ')
{
str1[i++]=ch;
ch=fgetc(fp1);
}
str1[i]='\0';
}
//puts(str1);
if(!(strcmp(str1,"define")))
{
i=0;
ch=fgetc(fp1);
while(ch!=' ' && ch!='\n')
{
str2[i++]=ch;
ch=fgetc(fp1);
}
str2[i]='\0';
}
}
} while(ch!= EOF);
fclose(fp1);
}
int main(void)
{
char ch;
int flag=1;
fp1=fopen("comm.txt","r");
fp2=fopen("new.txt","w");
mac();
do{
if(flag==0)
{
ch=fgetc(fp1);
}
if (ch!='#')
{
while(ch!='\n' && ch!=';')
{
i=0;
while(ch!=' ' && ch!='\n' && ch!=';')
{
str[i++]=ch;
ch=fgetc(fp1);
}
str[i]='\0';
//ch=fgetc(fp1);
if (!(strcmp(str,str1)))
fputs(str2,fp2);
else
fputs(str,fp2);
fputc(ch,fp1);
ch=fgetc(fp1);
}
fputc(ch,fp1);
if (ch=='\n')
flag=1;
else
flag =0;
}
else
{
while(ch!='\n')
{
fputc(ch,fp2);
ch=fgetc(fp1);
}
fputc(ch,fp2);
flag=1;
}
}while(ch!=EOF);
fclose(fp1);
fclose(fp2);
return EXIT_SUCCESS;
}