views:

1547

answers:

2

I have a file full of ascii data. How would I append a string to the first line of the file? I cannot find that sort of functionality using fopen (it seems to only append at the end and nothing else.)

+2  A: 

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

gnovice
Is there any way to use MATLAB variables for the filenames in the dos command?
temp2290
@temp2290: I added a discussion of that to my answer.
gnovice
+3  A: 

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')
Amro
+1: This fits with what I was thinking of for option #2, but I had a slightly different take on how to do it. I'll post for comparison.
gnovice