Как я могу заменить первое появление слова в файле?
Я пытаюсь заменить первое появление слова в файле, но другие файлы из argv не заменяются. Вот моя функция:
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); // char oldWord[100], newWord[100]; f= fopen("files_to_be_scanned.txt", "r"); while (!feof(f)) { fgets(file,sizeof(file),f); // file[strlen(file) - 1] = '\0'; 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"); } /* fopen() return NULL if unable to open file in given mode. */ if (fPtr == NULL || fTemp == NULL) { /* Unable to open file hence exit */ 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; // Bakup current line strcpy(temp, buff); // Index of current found word index = pos - buff; // Terminate str after word found index buff[index] = '\0'; // Concatenate str with new word strcat(buff, newWord); // Concatenate str with remaining words after // oldword found index. strcat(buff, temp + index + owlen); printf("TTTTTTTTTTTT %s\n",buff); fputs(buff, fTemp); } if(first_flag==1) { first_flag=0; break; } // printf("Afteeeeeeeeeeer %s\n",buff); } /* Close all files to release resource */ fclose(fPtr); fclose(fTemp); /* Delete original source file */ 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 temp file as original file */ rename("replace.txt", path); printf("\nSuccessfully replaced first occurrence of '%s' with '%s'.\n", oldWord, newWord); } }
а командная строка, с которой я выполняю это:
main replace -f I hoda -- file1.txt file2.txt
Что я уже пробовал:
Я старался не ставить взлома
if(first_flag==1) { first_flag=0; break; }
но другого пути я не нахожу.