How to Replace a line in a .TXT file
-
Hi.. How can we replace a line in a .TXT file using C++?? My aim is to replace a particular line in a ABC.TXT with another line from a ZYWV.TXT file?? Plz HELP ME!! Thanks.
User fscanf/fread to scan through the file and go to the required line Once the required line is found, use fseek to go back to the start of the line Do a fprintf/fwrite again. Keep in mind that if the new line is longer that the line in the file, it will overwrite entries in the next line. You will have to devise a appropriate insertion/modify strategy if the line lengths can be different.
-
Hi.. How can we replace a line in a .TXT file using C++?? My aim is to replace a particular line in a ABC.TXT with another line from a ZYWV.TXT file?? Plz HELP ME!! Thanks.
From ABC.TXT, write all lines up to the line to be replaced into a temporary file. Write the new line into the temporary file. Write the remaining lines from ABC.TXT into the temporary file. Delete ABC.TXT. Rename the temporary file to ABC.TXT. Make sense?
"The largest fire starts but with the smallest spark." - David Crow
"Judge not by the eye but by the heart." - Native American Proverb
-
Hi.. How can we replace a line in a .TXT file using C++?? My aim is to replace a particular line in a ABC.TXT with another line from a ZYWV.TXT file?? Plz HELP ME!! Thanks.
Try something like this (haven't tested this). ---------------------------------------------- #incluce #include #include int main(int argc, char* argv[]) { using namespace std; // Open files. ifstream inf("C:\\in.txt"); if (!inf) { cerr << "Failed to open input file" << endl; return 1; } ofstream outf("C:\\out.txt"); if (!outf) { cerr << "Failed to open output file" << endl; return 1; } // Copy the input file to the output file line by line replacing as needed. string line; while (getline(inf, line)) { if (line=="Replace this line") { outf << "With this line" << endl; } else { outf << line << endl; } } return 0; } Steve