I am trying to replace the first occurence of a word in a file but the other files from the argv are not replaced. Here is my function:
void replace_first(char* oldWord,char* newWord)
{
printf("f\n");
FILE * fPtr;
FILE * fTemp;
FILE* f;
char path[1000];
char file[BUFFER_SIZE];
char buff[BUFFER_SIZE];
char buff_2[BUFFER_SIZE];
printf("%d\n",num_files);
f= fopen("files_to_be_scanned.txt", "r");
while (!feof(f))
{
fgets(file,sizeof(file),f);
printf("\nfile is %s\n",file);
strcpy(path,file);
printf("path is %s\n",path);
path[strlen(path) - 1] = '\0';
fPtr = fopen(path, "r");
if(fPtr == NULL)
{
perror("error in main files");
}
fTemp = fopen("replace_4.txt", "w");
if(fTemp == NULL)
{
perror("error in replace file");
}
if (fPtr == NULL || fTemp == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
while ((fgets(buff, BUFFER_SIZE, fPtr)) != NULL)
{
printf("beforeeeee %s\n",buff);
char *pos,temp[BUFFER_SIZE];
int index = 0;
int owlen;
owlen = strlen(oldWord);
while ((pos = strstr(buff, oldWord)) != NULL)
{
first_flag=1;
strcpy(temp, buff);
index = pos - buff;
buff[index] = '\0';
strcat(buff, newWord);
strcat(buff, temp + index + owlen);
printf("TTTTTTTTTTTT %s\n",buff);
fputs(buff, fTemp);
}
if(first_flag==1)
{
first_flag=0;
break;
}
}
fclose(fPtr);
fclose(fTemp);
int del = remove(path);
if (!del)
{
printf("The file is Deleted successfully\n");
}
else
{
printf("the file is not Deleted\n");
perror("error in deleting file ");
}
rename("replace.txt", path);
printf("\nSuccessfully replaced first occurrence of '%s' with '%s'.\n", oldWord, newWord);
}
}
and the command line I execute with is:
main replace -f I hoda -- file1.txt file2.txt
What I have tried:
I have tried to not put break in
if(first_flag==1)
{
first_flag=0;
break;
}
but I do not find another way.