Copy a txt file to another text file in a defined position

3 vues (au cours des 30 derniers jours)
Nam Nguyen
Nam Nguyen le 20 Juil 2023
Commenté : Walter Roberson le 20 Juil 2023
I have two txt files. How to read a text in file 2 and then copy file 1 to file 2 under that text. Please help me. Thanks,
For example.
file 2:
hello
hi
How I copy file 1 to file 2 under the line "hello"?

Réponse acceptée

Walter Roberson
Walter Roberson le 20 Juil 2023
If you are using windows, then
system('copy file2.txt+file1.txt file2.txt')
The + is magic to Windows copy.exe to tell copy to append all of the given sources together.
Note: when you use copy like this, copy will not necessarily automatically put in an end-of-line between file2.txt and file1.txt in the case that file2.txt does not end with end-of-line.
  4 commentaires
Nam Nguyen
Nam Nguyen le 20 Juil 2023
Thanks Walter, so if I want to add file 1 to file 2 under the line "hello" in file 2. How do I modify this code.
Walter Roberson
Walter Roberson le 20 Juil 2023
Use readlines() on both files. Use startsWith or strcmp to search for the hello in the array for file2. Then form
[lines_for_file2(1:index_of_hello); lines_for_file1; lines_for_file2(index_of_hello+1:end)]
and writelines() that.
You might find that historically a lot of people assume that you can do the same task by using @doc:fopen() and loop fgetl on file2 until you find the key line, and then start fprintff or fwrite to write the lines for file1, with the assumption that doing so will somehow insert the lines for file1 inside of file2. That will not work.
In all systems since the day of Vax RMS (Record Management Services) from the early 1980s, text files are just continuous binary files with absolutely no overhead information about where to locate the lines. So if you start writing into the middle of an existing text file, you now always end up overwriting whatever is already there. There is absolutely no operating system support in the last 30 years for "inserting" text into the middle of a text file with the inserted text pushing the remaining data to later in the file. The only possibilities these days are to either rewrite the entire file, or else to do some careful buffering in memory in order to read ahead and store all of the data that will be overwritten by inserting the new text.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by