Uses of FILE pointer and Text File manipulation through C code
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
char *Update(char *s, char *prev, char *new)
{
int pLength = strlen(prev);
int nLength = strlen(new);
int count=0;
int i;
for(i=0; s[i]!='\0';++i)
{
if(strstr(&s[i],prev)== &s[i]){
++count;
i=i+pLength-1;
}
}
char *replace = (char *)malloc(i+count*(nLength-pLength)+1);
i=0;
while (*s)
{
if(strstr(s,prev)==s){
strcpy(&replace[i],new);
i+=nLength;
s+=pLength;
}
else{
replace[i++] = *s++;
}
}
replace[i] = '\0';
return replace;
}
int main()
{
FILE *ptr1=NULL;
FILE *ptr2=NULL;
char s[202];
char temp[30];
char *pointer;
ptr1 = fopen("input.txt","r");//read
ptr2 = fopen("output.txt","a");//append
if(ptr1==NULL) printf("File doesn't exist.\n");
fgets(s, 200, ptr1);
printf("Enter your name: ");
scanf(" %[^\n]s",temp);
pointer = Update(s,"{{name}}",temp);
// printf("%s\n",pointer);
printf("Enter your ID: ");
scanf(" %[^\n]s",temp);
pointer = Update(pointer,"{{id}}",temp);
// printf("%s\n",pointer);
printf("Enter your Department: ");
scanf(" %[^\n]s",temp);
pointer = Update(pointer,"{{Department}}",temp);
// printf("%s\n",pointer);
printf("%s\n",pointer);
fprintf(ptr2,"%s",pointer);
fclose(ptr1);
fclose(ptr2);
free(pointer);
return 0;
}
No comments