✔ 最佳答案
The following code is written with c-style input-output. But the logic is the same.
If you want, you simply replace them with the C++ style outptut.
#include < stdio.h>
#include < stdlib.h>
#include < string.h>
void fcopy(char *file1, char *file2)
{
FILE *f1=fopen(file1,"r"), *f2=fopen(file2,"w");
char li[200];
while(fgets(li,199,f1)!=NULL)fprintf(f2,"%s",li);
fflush(f2); fclose(f1); fclose(f2);
}
int main(int argc, char *argv[])
{
char li[200];
char *msg1="111";
char *file1="test_ios.txt", *file2="test_ios.tmp"; // open text and temp. files
FILE *f1=fopen(file1,"r"), *f2=fopen(file2,"w");
while(fgets(li,199,f1)!=NULL)
{
if(strncmp(li,"Username",8)==0) // use your own criteria for selecting the line
{
fprintf(f2,"%s",li); // write the line
fgets(li,199,f1); // read in next line
fprintf(f2,"%s\n",msg1); // dump line read, write replacement message
} else {
fprintf(f2,"%s",li); // copy line to output
}
}
fflush(f2); fclose(f1); fclose(f2);
fcopy(file2,file1); // copy temp file to original file, to be overwritten
gets(li); // halt display, press a key to continue
}
/* original content of test_ios.txt
Test
Username
888
abc
def
*/
/* final content of test_ios.txt
Test
Username
111
abc
def
*/