Lets say I have a .txt file that says:
Date: 01:10:21
Hi
My name is Jack
and I want to change My name is Jack
to My name is John
! but instead of change everything like:
file.open("yourname.txt", ios::out);
if (file.is_open()) {
file << "Date: 01:10:21 \nHi \nMy name is John";
file.close();
}
I want to edit only the Jack
part to John
, Because the date could be changed later that time, so how can I do it?
Every help appreciated!
CodePudding user response:
Can't say I know a proper C way, but there is a C way using <cstdio>
. Here is a snippet how this is achieved, however you need to implement your own logic for the problem, like finding where and how much to replace, ex. use indexes or string buffer to hold your needed data. Here is a minimum snippet:
#include <cstdio>
#include <cstring>
int main() {
FILE* fp = fopen("test.txt", "r ");
if (!fp)
return -1;
int c;
char buffer[30] = {0};
while (fgets(buffer, 3 /*hold `is `*/, fp)) {
printf("[%s]\r\n", buffer);
if (!strcmp(buffer, "is")) { //match `is` for example
fgetc(fp); // control the file ptr and move one forward
fputs("JOHN", fp); //replace
break;
}
}
fclose(fp);
return 0;
}