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

I have a file full of ascii data. How to add a line to the first line of a file? I cannot find such functionality using fopen (it seems to be added only at the end and nothing else.)

+6
file-io matlab text-files
source share
3 answers

Option 1:

I suggest calling some system commands from MATLAB . One of the features of Windows is to write a new line of text to its own file, and then use the DOS command to merge the two files . Here's what the call in MATLAB looks like:

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

I used it ! (bang) operator to invoke a command from MATLAB. The command above sequentially transfers the contents of the file "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you may have to end the first file with a new line character so that everything is appended correctly.

Another alternative to the specified command would be:

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

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

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

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

Option 2:

The only MATLAB solution besides Amro is:

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

It uses FILEREAD to read the contents of a text file in a line, combine the new line you want to add (along with the ASCII codes for carriage return and line / new line), then overwrite the original file with DLMWRITE .

I feel that Option # 1 might work faster than this pure MATLAB solution for huge text files, but I don't know for sure;)

+4
source share

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') 
+10
source share

How to use the frewind(fid) function to take a pointer to the beginning of a file?

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

But, a warning: it will be corresponded depending on what is on the first line. Since in my case I was the one who wrote the file, I put dummy data at the beginning of the file and then at the end, let it be overwritten after the above operations.

By the way, even I encountered one problem with this solution, that depending on the length (/ size) of the fictitious data and the actual data, the program either leaves part of the fictitious data on one line, or brings me new data in the second line. Any advice in this regard is much appreciated.

0
source share

All Articles