Writing a commented output to file

John W. Eaton jwe at octave.org
Tue May 5 10:09:41 CDT 2009


On  5-May-2009, AlexG1 wrote:

| Now, since the matrices can get quite big I don't want to use printf() for
| every line since it may take a lot of time. Ideally I'd like to use save
| -ascii to save the matrix and printf() for the comments.
| 
| The problem is this - if I'm using save to write the matrix first I can't
| prepend the comments since there is no way to open a file for prepending but
| only for appending.
| If I write the comments first and then call save -ascii it just overwrites
| the contents of the output file and the file will only contain the matrix
| without the comments.
| 
| Any ideas on how I can get both without just using printf() for everything?

Here's one more way:

  fid = fopen ('foo.dat', 'w');
  fprintf (fid, '%% Some comment 1\n%% Some comment 2\n');
  nc = size (x, 2);
  fmt = sprintf ('%s\n', repmat ('%f ', [1, nc]));
  fprintf (fid, fmt, x');
  fclose (fid);

I'm not sure whether it matters to you, but this method also has the
advantage of being compatible with the other leading brand.

jwe


More information about the Help-octave mailing list