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

조회 수: 6 (최근 30일)
Nam Nguyen
Nam Nguyen 2023년 7월 20일
댓글: Walter Roberson 2023년 7월 20일
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"?

채택된 답변

Walter Roberson
Walter Roberson 2023년 7월 20일
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
Nam Nguyen
Nam Nguyen 2023년 7월 20일
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 2023년 7월 20일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by