Hi,
I am also stuck with a problem in writing into the file .below explanation also helped me but my issue is yet not solved .I want to edit my file which looks like
IG_UDP_CPORTS="22,5060,5062"
TG_TCP_CPORTS="1,2,3"
EG_TCP_CPORTS="50,2"
IG_TCPP_CPORTS="60,62
IG_UDP_CPORTS="5060,5062"
I want to delete any value written in first line ( as m not able to edit any other line so i kept the line in first position to edit) say i want to delete 22 . After deletion my file first line looks like
IG_UDP_CPORTS="5060,5062"
2"
in next line there is some garbage value left
whole code is as follows,what i have done is i read first line from file and stored it in a string then did modifications in string and write modified string in file.
main(void)
{
FILE * fp,* fw;
char * line = NULL;
size_t len = 0,len1=0,len2=0;
char src[55],new_src[55];
char port[6];
int i,j,k,count=0,pos=0;
fp = fopen("conf.apf", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
fgets(src,50,fp);
len=strlen(src);
printf("\nEnter port number to be replaced : \n");
scanf("%s",port);
len1=strlen(port);
printf("%s and length of string %d\n", port,len1);
strncpy(new_src,src,len);
for (j=0; j<len1; j++)
for(i=15; i<len; i++)
{
if (port[j]==src[i])
{
j++;
printf("\nj=%d!!\n",j);
if(j==len1)
{
pos=i-len1;
printf("\nPort number matched !!\n");
break;
}
}
}
if (pos)
{
for(i=pos+1; i<len; i++)
new_src[i]=src[i+len1+1];
len2=strlen(new_src);
printf("\nNow string is %s and length of string %d", new_src,len2);
fw = fopen("conf.apf", "r+");
if (fw == NULL)
exit(EXIT_FAILURE);
fwrite(new_src,len2 ,1 ,fw);
printf( "\nport Removed successfully\n");
}
else
printf("\nPort number NOT matched !!\n");
fclose(fp);
fclose(fw);
exit(EXIT_SUCCESS);
}