3

I am trying to make a text file with the contents of a cell array. Below is a MWE. When I use fprintf without the file argument (to just print in the command window, e.g., fprintf(['\t\\hline ',repmat('%s & ',1,size(A,1)),'\b\b','\\\\','\n'],A{:})), the code works just fine. However, when I open a file with fopen and try to write the same thing to it, the double backspace (\b\b) does not work.

MWE:

A = num2cell(rand(3,3));
fid = fopen('test.txt','w');
fprintf(fid,['\t\\hline ',repmat('%s & ',1,size(A,1)),'\b\b','\\\\','\n'],A{:})

What I get in the command window:

\hline 7.922073e-01 & 9.594924e-01 & 6.557407e-01 \\
\hline 3.571168e-02 & 8.491293e-01 & 9.339932e-01 \\
\hline 6.787352e-01 & 7.577401e-01 & 7.431325e-01 \\

What I get in the 'test.txt' file:

\hline 7.922073e-01 & 9.594924e-01 & 6.557407e-01 & \\
\hline 3.571168e-02 & 8.491293e-01 & 9.339932e-01 & \\
\hline 6.787352e-01 & 7.577401e-01 & 7.431325e-01 & \\

And when pasting the contents of 'test.txt' to this question, rather than showing up exactly as they look in the .txt file, some boxes showed up where the backspaces should have been applied (figure below). How can I get the backspaces to work and delete & in the .txt file?

text

horchler
  • 18,384
  • 4
  • 37
  • 73
Rodrigues
  • 143
  • 1
  • 5

1 Answers1

3

I don't think that's how writing to a file normally works. fprintf writes each character it receives in sequence to a file without backtracking or interpreting the data. The raw byte value of '\b' (char(8)) doesn't represent a backspace in all files (e.g., in image/binary data). As you say, if you open the file in a true text editor (e.g., not Notepad or TextEdit) you'll see that it indeed includes the backspaces, likely represented as question marks or open boxes or "BS". Terminals, like the Matlab Command Window, generally pre-process text before displaying it. This page provides a bit of background.

I'm not aware of a way of changing this behavior of fprintf in Matlab. You either need to pre-process the text before it's printed to file or post-process the file to apply backspaces and rewrite.

To my mind, a more readable solution to this is:

A = num2cell(rand(3,3));
fid = fopen('test.txt','w');
str = repmat('%f & ',1,size(A,1));
fprintf(fid,['\t\\hline ',str(1:end-2),'\\\\','\n'],A{:});
fclose(fid);

You could also do something like this if you really want to keep the backspaces:

A = num2cell(rand(3,3));
fid = fopen('test.txt','w');
str = sprintf(['\t\\hline ',repmat('%f & ',1,size(A,1)),'\b\b','\\\\','\n'],A{:});
fprintf(fid,'%s',str);
fclose(fid);

If you use the code in your question and you're on a macOS or Linux machine, you can use the unix command to do something like this (from here) to write a new file with the backspaces applied:

unix('cat test.txt | col -b > test2.txt')
horchler
  • 18,384
  • 4
  • 37
  • 73