MATLAB: Как Вы вставляете строку текста в начале файла?

Flex и Flash имеют различные целевые аудитории. Flex более приспособлен к разработчикам, где, поскольку Flash более приспособлен к разработчикам и художникам.

6
задан Amro 9 June 2012 в 15:27
поделиться

2 ответа

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. ;)

4
ответ дан 8 December 2019 в 17:23
поделиться

Следующее - чистое решение MATLAB:

% 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')
10
ответ дан 8 December 2019 в 17:23
поделиться
Другие вопросы по тегам:

Похожие вопросы: