[英]Find and replace a word in a file, how to avoid reading the entire file into a buffer?
[英]How to replace a word in same file?
这是一个代码,它使用户能够替换另一个文件中的单词,但我想替换同一个文件中的单词。 每当用户输入要替换的单词时,该单词应该在同一个文件中被替换。 这个怎么做?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void findAndReplaceInFile() {
FILE *fr, *fw;
char word[100], ch, read[100], replace[100];
fr = fopen("file.txt", "r");
fw = fopen("new.txt", "w");
if (fr == NULL || fw == NULL) {
printf("Can't open file.");
exit(0);
}
printf("Enter the word to find: ");
fgets(word, 100, stdin);
word[strlen(word) - 1] = word[strlen(word)];
printf("Enter the word to replace it with: ");
fgets(replace, 100, stdin);
rewind(fr);
while (!feof(fr)) {
fscanf(fr, "%s", read);
if (strcmp(read, word) == 0) {
strcpy(read, replace);
}
fprintf(fw, "%s ", read);
}
fclose(fr);
fclose(fw);
}
int main() { findAndReplaceInFile(); }
我认为不可能直接在文件中进行更改,但是您可以给人一种您这样做的印象::)
尝试实现文件操作:
假设您有 file.txt(原始文件)和 new.txt(替换文件)
然后你可以删除file.txt
将 new.txt 重命名为 file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.