MATLAB: How do you insert a line of text at the beginning of a file?

南楼画角 提交于 2019-11-29 10:47:22
gnovice

Option 1:

I would suggest calling some system commands from within MATLAB. One possibility on Windows is to write your new line of text to its own file and then use the DOS for command to concatenate the two files. Here's what the call would look like in MATLAB:

!for %f in ("file1.txt", "file2.txt") do type "%f" >> "new.txt"

I used the ! (bang) operator to invoke the command from within MATLAB. The command above sequentially pipes the contents of "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you will probably have to end the first file with a new line character to get things to append correctly.

Another alternative to the above command would be:

!for %f in ("file2.txt") do type "%f" >> "file1.txt"

which appends the contents of "file2.txt" to "file1.txt", resulting in "file1.txt" containing the concatenated text instead of creating a new file.

If you have your file names in strings, you can create the command as a string and use the SYSTEM command instead of the ! operator. For example:

a = 'file1.txt';
b = 'file2.txt';
system(['for %f in ("' b '") do type "%f" >> "' a '"']);

Option 2:

One MATLAB only solution, in addition to Amro's, is:

dlmwrite('file.txt',['first line' 13 10 fileread('file.txt')],'delimiter','');

This uses FILEREAD to read the text file contents into a string, concatenates the new line you want to add (along with the ASCII codes for a carriage return and a line feed/new line), then overwrites the original file using DLMWRITE.

I get the feeling Option #1 might perform faster than this pure MATLAB solution for huge text files, but I don't know that for sure. ;)

The following is a pure MATLAB solution:

% write first line
dlmwrite('output.txt', 'string 1st line', 'delimiter', '')
% append rest of file
dlmwrite('output.txt', fileread('input.txt'), '-append', 'delimiter', '')
% overwrite on original file
movefile('output.txt', 'input.txt')
AamodG

How about using the frewind(fid) function to take the pointer to the beginning of the file?

I had a similar requirement and tried frewind() followed by the necessary fprintf() statement.

But, warning: It will overwrite on whichever is the 1st line. Since in my case, I was the one writing the file, I put a dummy data at the starting of the file and then at the end, let that be overwritten after the operations specified above.

BTW, even I am facing one problem with this solution, that, depending on the length(/size) of the dummy data and actual data, the program either leaves part of the dummy data on the same line, or bring my new data to the 2nd line.. Any tip in this regards is highly appreciated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!